leetcode114 二叉树展开为链表(Medium)

题目来源:leetcode114 二叉树展开为链表

题目描述:

给定一个二叉树,原地将它展开为一个单链表。

例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:

1
\
2
\
3
\
4
\
5
\
6

解题思路:

把右子树插入到左子树的最右结点的右边,再把左子树变为右子树。考虑新的右子树的根节点,重复上述过程,直至根节点为空。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        while(root!=NULL){
            //左子树为空,直接考虑下一个节点
            if(root->left==NULL){
                root=root->right;
            }
            else {
                TreeNode* pre=root->left;
                //找到左子树的最右节点
                while(pre->right!=NULL){
                    pre=pre->right;
                }
                pre->right=root->right;//把右子树插入到左子树的最右结点
                root->right=root->left;//将左子树插入到右子树的地方
                root->left=NULL;//左子树变为空
                root=root->right;//考虑下一个节点
            }
        }
    }
};
posted @ 2020-07-09 09:06  拉里拉里啦啦  阅读(137)  评论(0)    收藏  举报