码迷,mamicode.com
首页 > 其他好文 > 详细

Problem Flatten Binary Tree

时间:2014-07-07 18:47:24      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   strong   for   

Problem Description: Given a binary tree, flatten it to a linked list in-place.

Solution: 对二叉树进行前序遍历(pre-order).

 1 public void flatten(TreeNode root) {
 2         if (root == null) return;
 3         List<TreeNode> queue = new ArrayList<TreeNode>();
 4         Stack<TreeNode> stack = new Stack<TreeNode>();
 5         stack.push(null);
 6         TreeNode top  =root;
 7         while (top != null) {
 8             queue.add(top);
 9             if (top.right != null) stack.push(top.right);
10             if (top.left != null) stack.push(top.left);
11             top = stack.pop();
12         }
13 
14         for (int i = 0; i < queue.size(); i++) {
15             TreeNode node = queue.get(i);
16             node.left = null;
17             if (i < queue.size() - 1)  
18                 node.right = queue.get(i+1);
19         }
20     }

 

Problem Flatten Binary Tree,布布扣,bubuko.com

Problem Flatten Binary Tree

标签:des   style   blog   color   strong   for   

原文地址:http://www.cnblogs.com/liew/p/3813376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!