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

题目

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

 

C++代码

/**
 * 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:
    TreeNode* convertBST(TreeNode* root) {
        if(root)
            fun(root, 0);
        return root;
    }
    int fun(TreeNode* root, int sum)
    {
        if(root->right)
        {
            sum = fun(root->right, sum);
        }
        int val = root->val;
        root->val += sum;
        sum += val;
        if(root->left)
        {
             sum = fun(root->left, sum);
        }
        return sum;
    }
};

 

上一篇:LeetCode 把二叉搜索树转换为累加树(538)


下一篇:538. 把二叉搜索树转换为累加树