zoukankan      html  css  js  c++  java
  • [leetcode]114. Flatten Binary Tree to Linked List将二叉树展成一个链表

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

    For example, given the following tree:

        1
       / 
      2   5
     /    
    3   4   6
    

    The flattened tree should look like:

    1
     
      2
       
        3
         
          4
           
            5
             
              6

    题目

    将左子树所形成的链表插入到root和root->right之间

    思路

          1
       /         
      2(root)              假设当前root为2
     /        
    3(p)  4     

          1
       /         
      2(root)   
     /          
    3(p)—— 4(root.right)    p.right = root.right

         1
        /         
        2(root)   
     /         
    3(root.right)- 4      root.right = root.left

          1
        /         
        2(root)   
               
    3(root.right)- 4      root.left - null



    代码

     1 class Solution {
     2     public void flatten(TreeNode root) {
     3         if (root == null) return;  // 终止条件
     4         // recursion
     5         flatten(root.left);
     6         flatten(root.right);
     7 
     8         if (root.left == null) return;
     9 
    10         // 三方合并,将左子树所形成的链表插入到root和root->right之间
    11         TreeNode p = root.left;
    12         while(p.right != null) {
    13             p = p.right; //寻找左链表最后一个节点
    14         } 
    15         p.right = root.right;
    16         root.right = root.left;
    17         root.left = null;
    18     }
    19 }
  • 相关阅读:
    Spring:dispatchservlet
    信息系统设计
    数据流图的绘制方法
    信息系统管理工程师学习笔记
    JS语法学习笔记
    jQuery
    用Excel生成Sql
    JAVA-Reflect
    Java创建对象的过程
    有关死锁那点事儿
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9823988.html
Copyright © 2011-2022 走看看