LeetCode HOT100 - 把二叉搜索树转换为累加树

因为搜索树

左侧一定小于,右侧一定大于

那么从结果上来说的话就是左子树的值应该是自身加上根节点及右子树

其他的都是右节点

但是树的问题只能自底向上或者自顶向下

对于左子树需要上一层,右子树需要下一层这样的情况用 dfs 显然不太好做

但是先左->根->右这样的大小关系想到了中序遍历

如果我们有中序遍历的结果,那倒着跑一遍维护和不就有了对应的结果了吗

/**
 * 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:
    TreeNode* convertBST(TreeNode* root) {
        vector<TreeNode*> a;
        auto dfs = [&](this auto&& self, TreeNode* u) -> void {
            if (!u) {
                return;
            }
            self(u->left);
            a.emplace_back(u);
            self(u->right);
        };
        dfs(root);
        int n = a.size();
        for (int i = 0; i < n; i++) {
            cout << a[i]->val << " \n"[i == n - 1];
        }
        int cur = 0;
        for (int i = n - 1; i >= 0; i--) {
            cur += a[i]->val;
            a[i]->val = cur;
        }
        return root;
    }
};

正解也是中序遍历,不过确实不需要单独把这个数组维护出来

但是这里还提到了一个 Morris 遍历的方法,下次学一下

posted @ 2026-04-15 22:24  rdcamelot  阅读(11)  评论(0)    收藏  举报