• 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 flatten(TreeNode *root) {
    13         // IMPORTANT: Please reset any member data you declared, as
    14         // the same Solution instance will be reused for each test case.
    15         if(root == NULL)return ;
    16         stack<TreeNode *> S;
    17         S.push(root);
    18         TreeNode *pre = NULL;
    19         while(S.empty() == false)
    20         {
    21             TreeNode *p = S.top();
    22             S.pop();
    23             if(pre != NULL)
    24             {
    25                 pre->right = p;
    26                 pre->left = NULL;
    27             }
    28             if(p->right)S.push(p->right);
    29             if(p->left)S.push(p->left);
    30             pre = p;
    31         }
    32         pre->left = NULL;
    33         pre->right = NULL;
    34     }
    35 };

    【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3440032.html

  • 相关阅读:
    设计模式学习
    rabbitMQ topic实现广播
    rabbitMQ direct实现广播
    rabbitMQ fanout 实现广播
    rabbitMQ 生产者消费者
    python select 实现IO异步
    python gevent 爬虫
    python gevent socket
    python 协程
    python 进程池
  • 原文地址:https://www.cnblogs.com/TenosDoIt/p/3440032.html
Copyright © 2020-2023  润新知