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
    

    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.

    思路一:递归的思想。使用后序递归的方法。先将左右子树转换为链表,再将左右子树连接

         时间复杂度O(n),空间复杂度O(logN)

     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 == nullptr) return;
    14         
    15         flatten(root->left);
    16         flatten(root->right);
    17         
    18         //三方合并,将左子树形成的链表插入到root和root->right之间
    19         TreeNode *p = root->right;
    20         while (p->right) p = p->right;
    21         p->right = root->right;
    22         root->right = root->left;
    23         root->left = nullptr;
    24     }
    25 };

    思路二:迭代的方法。依据题目与前序遍历之间的关系。使用前序遍历的方法。

        

     1 void flatten(TreeNode *root) {
     2         if(root == NULL) return;
     3     while(root){
     4         if(root->left){
     5             TreeNode *pre = root->left;
     6             while(pre->right)
     7                 pre = pre->right;
     8             pre->right = root->right;
     9             root->right = root->left;
    10             root->left = NULL;
    11         }
    12         root = root->right;
    13     }
    14     }
  • 相关阅读:
    python之各种包
    正则表达式
    import/模块的导入
    迭代器/可迭代对象/生成器
    Day2 列表list
    Day1 字符串格式化
    Day1 字符编码及编码函数
    Python 学习笔记 之 随着学习不断更新的Python特性搜集
    Day1 input&print
    Newtonsoft.Json日期转换
  • 原文地址:https://www.cnblogs.com/vincently/p/4231048.html
Copyright © 2011-2022 走看看