LeetCode OJ - Flatten Binary Tree to Linked List

这题的提示中给出,linked list是原来二叉树的先序遍历。所以我用一个栈暂时存储每个节点的右子树(如果它有右子树的话),然后把左子树交换到右子树,左节点置为null,之后迭代下去,当遇到叶子节点时,从栈中pop出一个子树,再继续,直到遇到叶子节点且栈中为空。

下面是AC代码:

 1  /**
 2      * Given a binary tree, flatten it to a linked list in-place.
 3      * If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
 4      * @param root
 5      */
 6     public void flatten(TreeNode root){
 7         if(root == null || root.left==null && root.right == null)
 8             return;
 9         //the stack is for the right children
10         LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
11         TreeNode temp = root;
12         while(true){
13             if(temp.left!=null)
14             {
15                 if(temp.right!=null)
16                     stack.push(temp.right);
17                 temp.right = temp.left;
18                 temp.left = null;
19                 
20             }
21             if(temp.right != null)
22                 temp = temp.right;
23             if(temp.left == null && temp.right == null){
24                 if(stack.isEmpty())
25                     break;
26                 temp.right = stack.pop();
27                 temp = temp.right;
28             }
29         }
30         
31     }

 

posted @ 2014-05-04 21:21  echoht  阅读(122)  评论(0编辑  收藏  举报