114. Flatten Binary Tree to Linked List

1. 蠢蠢的方法,dfs保存,重新构造

 1   public void flatten(TreeNode root) {
 2         if(root == null) {
 3             return;
 4         }
 5         Stack<TreeNode> stack = new Stack<TreeNode>();
 6         LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
 7         stack.push(root);
 8         while(!stack.isEmpty()) {
 9             TreeNode cur = stack.pop();
10             nodes.add(cur);
11             if(cur.right != null) {
12                 stack.push(cur.right);
13             }
14             if(cur.left != null) {
15                 stack.push(cur.left);
16             }
17             
18         }
19         TreeNode pre = nodes.poll();
20         while(!nodes.isEmpty()) {
21             pre.left = null;
22             TreeNode cur = nodes.poll();
23             pre.right = cur;
24             pre = cur;
25         }
26      }

2. 用递归,如果右节点不是空的就先保存下来,然后root的右节点等于左节点,左节点清空,cur的节点要么是root的右节点(即原先的左节点),要么就从栈里弹一个出来,递归

 1     public void flatten(TreeNode root) {
 2         if(root == null) {
 3             return;
 4         }
 5         Stack<TreeNode> stack = new Stack<TreeNode>();
 6         helper(root, stack);
 7      }
 8      
 9      private void helper(TreeNode root, Stack<TreeNode> stack) {
10          if(root == null) {
11              return;
12          }
13          TreeNode right = root.right;
14          if(right != null) {
15              stack.push(right);
16          }
17          TreeNode cur = null;
18          if(root.left == null) {
19              if(!stack.isEmpty()) {
20                  cur = stack.pop();
21              } else {
22                  return;
23              }
24          } else {
25              cur = root.left;
26          }
27          root.right = cur;
28          root.left = null;
29          helper(cur, stack);
30      }

3. code ganker 

ref:http://blog.csdn.net/linhuanmars/article/details/23717703

 1 public void flatten(TreeNode root) {  
 2     ArrayList<TreeNode> pre = new ArrayList<TreeNode>();  
 3     pre.add(null);  
 4     helper(root, pre);  
 5 }  
 6 private void helper(TreeNode root, ArrayList<TreeNode> pre)  
 7 {  
 8     if(root == null)  
 9         return;  
10     TreeNode right = root.right;  
11     if(pre.get(0)!=null)  
12     {  
13         pre.get(0).left = null;  
14         pre.get(0).right = root;  
15     }  
16     pre.set(0,root);  
17     helper(root.left, pre);  
18     helper(right, pre);  
19 }  

 

posted @ 2016-06-14 05:58  warmland  阅读(144)  评论(0编辑  收藏  举报