538. Convert BST to Greater Tree

2018/05/01 leetcode 共 646 字,约 2 分钟

Title

the problem link

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this: 5 /
2 13

Output: The root of a Greater Tree like this: 18 /
20 13

对二叉排序树,把每个节点的值设置为比它大的节点的总和,因此需要先right,再left

Solution

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

Search

    Table of Contents