114. Flatten Binary Tree to ed List

Medium

Given a binary tree, flatten it to a ed list in-place.

For example, given the following tree:

    1
   / \\
  2   5
 / \\   \\
3   4   6

The flattened tree should look like:

1
 \\
  2
   \\
    3
     \\
      4
       \\
        5
         \\
          6

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        if (null != root) {
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode node = stack.pop();

                if (node.right != null) {
                    stack.push(node.right);
                }
                if (node.left != null) {
                    stack.push(node.left);
                }
                
                node.right = stack.isEmpty() ? node.right : stack.peek();
                node.left = null;
            } 
        }

    }
}

 

收藏 打印