zoukankan      html  css  js  c++  java
  • [Leetcode] 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 binary tree
     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 helper(TreeNode *root, TreeNode *&pre) {
    13         if (root == NULL) return;
    14         if (pre != NULL) {
    15             pre->left = NULL;
    16             pre->right = root;
    17         }
    18         pre = root;
    19         TreeNode *left = root->left;
    20         TreeNode *right = root->right;
    21         if (left != NULL) {
    22             helper(left, pre);
    23         }
    24         if (right != NULL) {
    25             helper(right, pre);
    26         }
    27     }
    28     void flatten(TreeNode *root) {
    29         TreeNode *pre = NULL;
    30         helper(root, pre);
    31     }
    32 };

     非递归的话,可以先让当前节点的右儿子指向左儿子,左儿子的最右儿子指向当前节点的原来的右儿子,依次迭代即可。

     1 /**
     2  * Definition for binary tree
     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         if (root == NULL) return;
    14         TreeNode *cur = root, *pre = NULL;
    15         while (cur != NULL) {
    16             if (cur->left != NULL) {
    17                 pre = cur->left;
    18                 while (pre->right) pre = pre->right;
    19                 pre->right = cur->right;
    20                 cur->right = cur->left;
    21                 cur->left = NULL;
    22             }
    23             cur = cur->right;
    24         }
    25     }
    26 };
  • 相关阅读:
    fastjson转对象的一些属性设置
    Linux下重命名文件或文件夹(mv命令与rename命令)
    Linux下打包压缩war、解压war包和jar命令
    linux如何复制文件夹和移动文件夹
    linux下使用tar命令
    linux压缩和解压缩命令大全
    2019第11周日
    Git上传空文件夹的方法
    SpringBoot2
    Spring Boot 历史
  • 原文地址:https://www.cnblogs.com/easonliu/p/3646841.html
Copyright © 2011-2022 走看看