leetcode 538.把二叉树转换为累加树

leetcode 538.把二叉树转换为累加树

题干

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

例如:

输入: 原始二叉搜索树:
5
/
2 13

输出: 转换为累加树:
18
/
20 13

题解

想着就是个逆向的中序遍历
* 效率一般
* 还要复习一下中序遍历,顺带复习一下线索树

class Solution {
    
    
public:
    int sum = 0;
    void dfs(TreeNode* root){
    
    
        if(root!=NULL)
        {
    
    
            dfs(root->right);
            int temp = root->val;
            root->val += sum;
            sum += temp;
            dfs(root->left);
        }
        return;
    }
    TreeNode* convertBST(TreeNode* root) {
    
    
        auto ans = root;
        dfs(root);
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43662405/article/details/108720975