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

Flatten Binary Tree to Linked List

时间:2014-12-12 22:06:12      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

Flatten Binary Tree to Linked List 

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
这道题,先先序遍历整棵树,在遍历的时候,构造一棵只有右子树的树。将root指向这颗新生成的树即可。
 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     TreeNode newTree = null;
12     
13     public void flatten(TreeNode root) {
14         if(null == root)
15             return;
16         preOrder(root);
17         root.right = newTree.right;
18         root.left = null;
19     }
20     
21     /**
22      *     前序遍历一棵树,生成一棵只有右子树的树
23      * @param root
24      * @return
25      */
26     public void preOrder(TreeNode root){
27         if(null != root){
28             if(newTree == null){                        //新树的根节点如果为空
29                 newTree = new TreeNode(root.val);
30             }    
31             else{                                        //根节点不为空
32                 TreeNode temp = newTree;
33                 
34                 while(temp.right != null)
35                     temp = temp.right;                    //找到插入点
36                 temp.right = new TreeNode(root.val);    //在右子树插入结点                
37             }
38             preOrder(root.left);                        //遍历左子树
39             preOrder(root.right);                        //遍历右子树
40         }
41     }
42 }

 

Flatten Binary Tree to Linked List

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/luckygxf/p/4160486.html

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