zoukankan      html  css  js  c++  java
  • 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
    先对二叉树进行前序排列,然后放进一个只有右支树的二叉树中
     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param root: a TreeNode, the root of the binary tree
    15      * @return: nothing
    16      */
    17     public void flatten(TreeNode root) {
    18         // write your code here
    19         if (root == null)   return;  
    20         TreeNode cur =  root , pre = null;
    21         while(cur != null){  //当前节点不为空
    22             if ( cur.left != null){  //当前节点有左儿子
    23                 pre = cur.left;   
    24                 while ( pre.right !=null ) pre = pre.right;  //当前节点的右儿子指向左儿子,左儿子的最右儿子指向当前节点的右儿子
    25                 pre.right = cur.right;
    26                 cur.right = cur.left;
    27                 cur.left  = null;
    28             }
    29             cur=cur.right;
    30         }
    31     }
    32 }
  • 相关阅读:
    第六章 条件处理
    VS2019配置MKL教程(Windows)
    攻防世界--srm-50
    攻防世界--The_Maya_Society
    攻防世界--re1-100
    BUUCTF--findit
    凯撒加密与解密实现
    BUUCTF--rsa
    正则表达式
    PyQuery详解
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/4951193.html
Copyright © 2011-2022 走看看