• leetcode------Flatten Binary Tree to Linked List


    标题: Flatten Binary Tree to Linked List
    通过率: 28.7%
    难度: 中等

    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
    

    click to show hints.

    Hints:

    If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

    本题就是把一颗树变成退化树

    都是只有右孩子,那么需要操作的就是找到左孩子的最有节点,将root的右树连接到左孩子的最右节点,然后root的右孩子指向左孩子,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     public void flatten(TreeNode root) {
    12        while(root!=null){
    13            if(root.left!=null){
    14             TreeNode tmp=root.left;
    15             while(tmp.right!=null)
    16                 tmp=tmp.right;
    17             tmp.right=root.right;
    18             root.right=root.left;
    19             root.left=null;
    20            }
    21             root=root.right;
    22        }
    23     }
    24 }
  • 相关阅读:
    AcWing 199. 余数之和
    AcWing 295. 清理班次
    AcWing 294. 计算重复
    Acwing 393. 雇佣收银员
    AcWing 362. 区间
    AcWing 361. 观光奶牛
    CSP-S 2019 Emiya 家今天的饭
    CSP-S 2019游记
    AcWing 345. 牛站 Cow Relays
    java 环境配置
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4333946.html
Copyright © 2020-2023  润新知