LeetCode 八月打卡day2 114. 二叉树展开为链表(递归)

题目链接

在这里插入图片描述
依据二叉树展开为链表的特点,使用后序遍历完成展开。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    void flatten(TreeNode* root) {
    
    
        if(root==NULL) return;
        while(root!=NULL)
        {
    
    
            if(root->left!=NULL)
            {
    
    
                TreeNode* tp=root->left;
                while(tp->right!=NULL)
                    tp=tp->right;
                tp->right=root->right;
                root->right=root->left;
                root->left=NULL;
            }
            root=root->right;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43663263/article/details/107788074