LeetCode 538 Convert BST to Greater Tree

标签: 二叉搜索树 LeetCode 发布于:2022-02-07 10:07:19 编辑于:2022-02-07 10:08:17 浏览量:1035

概述

https://leetcode.com/problems/convert-bst-to-greater-tree/

https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/

直接法

先遍历右子树,得到其和,算出当前节点的值,再遍历左子树。

class Solution {
public:
    int last = 0;
    TreeNode* convertBST(TreeNode* root) {
        helper(root);
        return root;
    }
    
    void helper(TreeNode* root) {
        if (!root) return;
        helper(root->right);
        root->val += last;
        last = root->val;
        helper(root->left);
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/