LeetCode 538. Convert BST to Greater Tree

来源:互联网 发布:厦门软件著作权申请 编辑:程序博客网 时间:2024/05/21 06:35

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

BST 一般会用到中序遍历~

/** * 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:    // vector<int> v;     // void inOrderBST(TreeNode* root)    // {    //     if(!root)    //         return;    //     inOrderBST(root->left);    //     v.push_back(root->val);    //     inOrderBST(root->right);    // }    // int i = 0, sum = 0;    // TreeNode* rebuiltBST(TreeNode* root)    // {    //     if(!root)    //         return root;    //     rebuiltBST(root->left);    //     sum -= v[i++];    //     root->val = sum;    //     rebuiltBST(root->right);    //     return root;    // }    int sum = 0;    TreeNode* convertBST(TreeNode* root) {        // v.push_back(0);        // inOrderBST(root);        // for(int j=0;j<v.size();++j)        //     sum += v[j];        // return rebuiltBST(root);        if(!root)            return root;        convertBST(root->right);        sum += root->val;        root->val = sum;        convertBST(root->left);        return root;    }};
原创粉丝点击