首页 > 其他 > 详细

Problem Flatten Binary Tree

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!