Leetcode 1038. Convert binary search tree to accumulative tree

Leetcode 1038. Convert binary search tree to accumulative tree

topic

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。
注意:该题目与 538: https://leetcode-cn.com/problems/convert-bst-to-greater-tree/  相同

Example 1:

Insert picture description here

输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

Example 2:

输入:root = [0,null,1]
输出:[1,null,1]

Example 3:

输入:root = [1,0,2]
输出:[3,3,2]

Example 4:

输入:root = [3,2,4,1]
输出:[7,9,4,10]

Ideas

  • Basically, the tree problem can be handled by recursion, this problem is also the same idea
  • Since the in-order traversal of the binary search tree meets the characteristics of increasing, this problem can be considered using in-order traversal
  • If it is left->root->right, you will find that it is not easy to write, but if you change it to the order of right->root->left, when you traverse to root, you will have all the nodes greater than or equal to root->val It's all over

Code

/**
 * 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 dfs(TreeNode* root, int& sum) {
        if (!root) return;

        dfs(root->right, sum);
        sum += root->val;
        root->val = sum;
        dfs(root->left, sum);
    }

    TreeNode* bstToGst(TreeNode* root) {
        int sum = 0;
        dfs(root, sum);
        return root;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43891775/article/details/112169445