zoukankan      html  css  js  c++  java
  • LeetCode OJ: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 for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void flatten(TreeNode* root) {
    13         while(root){
    14             if(root->left){
    15                 TreeNode * leftBegin = root->left;
    16                 root->left = NULL;
    17                 TreeNode * leftEnd = leftBegin;
    18                 while(leftEnd->right)
    19                     leftEnd = leftEnd->right;
    20                 TreeNode * tmpRight = root->right;
    21                 root->right = leftBegin;
    22                 leftEnd->right = tmpRight;
    23             }
    24             root = root->right;
    25         }
    26     }
    27 };

     用java写了一遍,方法与上面基本相同,代码如下:

     1 /**
     2  * Definition for a binary tree node.
     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.right;
    15                 root.right = root.left;
    16                 TreeNode tmpRight = root.right;
    17                 while(tmpRight.right != null)
    18                     tmpRight = tmpRight.right;
    19                 tmpRight.right = tmp;
    20                 root.left = null;
    21             }
    22             root = root.right;
    23         }
    24     }
    25 }
  • 相关阅读:
    面试官:你说说互斥锁、自旋锁、读写锁、悲观锁、乐观锁的应用场景
    JAVA 线上故障排查套路,从 CPU、磁盘、内存、网络到GC 一条龙!
    面经分享:看非科班研究生如何转行斩获 ATM 大厂的 Offer ?
    Jmeter JDBC配置
    Jmeter JDBC连接
    js基础用法1
    java实现io读取数据
    mysql语句
    java修改linux文件
    linux永久或临时修改dns
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4909780.html
Copyright © 2011-2022 走看看