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 };
  • 相关阅读:
    mvc get image 500
    git ssh 配置
    phpstorm及webstorm密钥
    HBuilder常用快捷键
    【wepy实战】wepy搭建完整项目
    【已解决】React中配置Sass引入.scss文件无效
    【微信小程序入门】微信小程序+和风天气完成天气预报
    浅析C#中的Lambda表达式
    C#中的委托(delegate)
    博客园第一天
  • 原文地址:https://www.cnblogs.com/easonliu/p/3646841.html
Copyright © 2011-2022 走看看