zoukankan      html  css  js  c++  java
  • leetcode-114. 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

    思路:递归处理,引用二叉链表的思想,使用pre记录上一个分支的指针。

    Accepted Code:
     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 private:
    12     TreeNode* pre=nullptr;
    13 public:
    14     void flatten(TreeNode* root) {
    15         if(root==nullptr)
    16         return;
    17         flatten(root->right);
    18         flatten(root->left);
    19         root->right=pre;
    20         root->left=nullptr;
    21         pre=root;
    22     }
    23 };
  • 相关阅读:
    并查集
    强联通分量,缩点
    最短路径
    最小生成树
    拓扑排序
    图的遍历
    图论基础知识
    数据库四种隔离级别
    MySQL 索引 乐观锁 悲观锁
    MYSQL+正则
  • 原文地址:https://www.cnblogs.com/hongyang/p/6423405.html
Copyright © 2011-2022 走看看