欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

114. 二叉树展开为链表

程序员文章站 2024-03-26 14:12:29
...

114. 二叉树展开为链表

题解:特殊的后序遍历,右->左->中

https://leetcode.wang/leetcode-114-Flatten-Binary-Tree-to-Linked-List.html

/**
 *  * 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) {
        TreeNode* pre = nullptr;
        back_order(root, pre);
    }
    void back_order(TreeNode* root, TreeNode*& pre) {
        if(root == nullptr) {
            return;
        }
        back_order(root->right, pre);
        back_order(root->left, pre);
        root->right = pre;
        root->left = nullptr;
        pre = root;
    }
};

 

相关标签: leetcode