661.Convert BST to Greater Tree

来源:互联网 发布:淘宝卖家为什么改价格 编辑:程序博客网 时间:2024/05/20 05:58

题目:

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.


样例

Given a binary search Tree `{5,2,3}`:

              5            /   \           2     13

Return the root of new tree

             18            /   \          20     13

代码:

class Solution {public:    /**     * @param root the root of binary tree     * @return the new root     */        // Write your code here    int sum=0;      void travel(TreeNode* root)      {          if(root==NULL) return ;          if (root->right)          {            travel(root->right);          }            sum+=(root->val);              root->val=sum;        if (root->left)          {            travel(root->left);        }    }      TreeNode* convertBST(TreeNode* root) {          travel(root);          return root;      }  };  


思想:从右往左递归累计加值,然后复制给当前节点。

0 0