其他分享
首页 > 其他分享> > leetcode 1038. 从二叉搜索树到更大和树

leetcode 1038. 从二叉搜索树到更大和树

作者:互联网

目录

题目描述:

给出二叉搜索树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

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

示例:

输入:[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]

提示:


解法:

/**
 * 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:
    int updateTree(TreeNode*& root, int val){
        if(root == NULL){
            return val;
        }else{
            int right = updateTree(root->right, val);
            root->val += right;
            int left = updateTree(root->left, root->val);
            return left;
        }
    }
    
    TreeNode* bstToGst(TreeNode* root) {
        int val = 0;
        updateTree(root, val);
        return root;
    }
};

标签:树到,TreeNode,val,int,节点,1038,null,root,leetcode
来源: https://www.cnblogs.com/zhanzq/p/11075889.html