zoukankan      html  css  js  c++  java
  • Flatten Binary Tree to Linked List

    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 }
  • 相关阅读:
    C++:new&delete
    C++:模板——函数模板1
    C/C++:static用法总结
    C++:内存分区
    C++:友元
    C++:构造函数3——浅拷贝和深拷贝
    C++:类中两个易被忽略的默认函数
    C++:析构函数
    C++:类中的赋值函数
    SHELL基础知识
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4160486.html
Copyright © 2011-2022 走看看