• leetcode114- 二叉树展开为链表


     1 /*
     2  * @lc app=leetcode.cn id=114 lang=cpp
     3  *
     4  * [114] 二叉树展开为链表
     5  */
     6 
     7 // @lc code=start
     8 /**
     9  * Definition for a binary tree node.
    10  * struct TreeNode {
    11  *     int val;
    12  *     TreeNode *left;
    13  *     TreeNode *right;
    14  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
    15  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    16  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    17  * };
    18  */
    19 class Solution {
    20 public:
    21 
    22     //题解1:前序遍历将二叉树转换为链表,
    23     // void flatten(TreeNode* root) {
    24     //     root=build(root);
    25     // }
    26     // TreeNode* build(TreeNode* root){
    27     //     if(root==nullptr) return nullptr;
    28     //     TreeNode* head=new TreeNode(0);
    29     //     stack<TreeNode*> st;
    30     //     st.push(root);
    31     //     while(!st.empty()){
    32     //        TreeNode* t=st.top();
    33     //         head->right=t;
    34     //         st.pop();
    35     //         head->left=nullptr;
    36     //         if(root->right) st.push(t->right);
    37     //         if(root->left) st.push(t->left);
    38     //         head=head->right;
    39     //     }
    40     //     return head->right;
    41     // }
    42 
    43     ////题解2:将右子树连接到左子树的最右边节点上,然后左子树移动到原来右子树的地方,最后将根节点的左子树赋为空
    44     void flatten(TreeNode* root) {
    45         while(root!=nullptr){
    46             if(root->left==nullptr)//左子树为空, 考虑下一个节点
    47                 root=root->right;
    48             else{
    49                 TreeNode* pre=root->left;
    50                 while(pre->right!=nullptr)// 寻找左子树最右边的节点
    51                     pre=pre->right;
    52                 pre->right=root->right;//右子树连接到左子树的最右边节点上
    53                 root->right=root->left;// 更新根节点的右子树
    54                 root->left=nullptr;//左子树赋为空
    55                 root=root->right;// 考虑下一个节点
    56             }
    57         }
    58     }
    59 };
    60 // @lc code=end
  • 相关阅读:
    模拟测试20190815(已更新)
    [JLOI2015]管道连接
    [BJWC2018]最长上升子序列
    [CQOI2012]局部极小值
    [HNOI2010]Bus 公交线路
    [BZOJ4903/CTSC2017]吉夫特
    [BZOJ3717/PA2014]Pakowanie
    [NOI2015]寿司晚宴
    [BZOJ4145/AMPPZ2014]The Prices
    [Usaco2013 Nov]No Change
  • 原文地址:https://www.cnblogs.com/yaodao12/p/13950943.html
Copyright © 2020-2023  润新知