码迷,mamicode.com
首页 > 编程语言 > 详细

Flatten Binary Tree to Linked List leetcode java

时间:2014-07-24 09:55:43      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   使用   

题目:

 

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

For example,
Given

         1
        /        2   5
      / \        3   4   6
The flattened tree should look like:
   1
         2
             3
                 4
                     5
                         6

题解
如hint所给出,这道题就是使用先序遍历,遍历到的值作为新的右孩子存起来,左孩子变为空。
注意的是,因为右孩子会更新,所以为了递归右子树,要在更新之前提前保存右孩子。
整个程序需要维护一个全局变量,保存当前所遍历的节点。

代码如下:
 1   TreeNode lastvisited = null;
 2     public void flatten(TreeNode root) {
 3         if(root == null)
 4             return;
 5         
 6         TreeNode realright = root.right;
 7         if(lastvisited != null){
 8             lastvisited.left = null;
 9             lastvisited.right = root;
10         }
11         
12         lastvisited = root;
13         flatten(root.left);
14         flatten(realright);
15     }
Reference:http://blog.csdn.net/perfect8886/article/details/20000083

此题还有不用递归方法解决的方法,那就是使用栈。
对整棵树一直向右子树方向遍历。当遍历的节点有右孩子时,就将其入栈。有左孩子时,将其更新为当前节点的右孩子,左孩子置空。当左孩子为空时而栈不空时,
就弹出栈,作为右孩子。代码如下:
 1     public void flatten(TreeNode root) {
 2         Stack<TreeNode> stack = new Stack<TreeNode>();
 3         TreeNode p = root;
 4  
 5         while(p != null || !stack.empty()){
 6  
 7             if(p.right != null){
 8                 stack.push(p.right);
 9             }
10  
11             if(p.left != null){
12                 p.right = p.left;
13                 p.left = null;
14             }else if(!stack.empty()){
15                 TreeNode temp = stack.pop();
16                 p.right=temp;
17             }
18  
19             p = p.right;
20         }
21     }
Reference: //http://www.programcreek.com/2013/01/leetcode-flatten-binary-tree-to-linked-list/

Flatten Binary Tree to Linked List leetcode java,布布扣,bubuko.com

Flatten Binary Tree to Linked List leetcode java

标签:style   blog   http   java   color   使用   

原文地址:http://www.cnblogs.com/springfor/p/3864355.html

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