您的位置:首页 > 其它

Convert BST to Greater Tree-LintCode

2017-05-21 21:57 375 查看
描述:

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


思路:

基于二叉排序树的性质,即根节点的左子树上的节点都小于根节点,右子树上的节点都大于根结点。

所以这个题就需要从最右边的叶子节点开始访问,因为它是整棵树中最大的节点,访问顺序为 右子树->根节点->左子树。

在访问一个节点时依序加上之前访问过的节点,谁让那些节点都比它大呢!

AC代码:

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @return the new root
*/
int sum=0;
void add(TreeNode* root)
{
if(root==NULL)
return ;
add(root->right);
root->val=root->val+sum;
sum=root->val;
add(root->left);
}
TreeNode* convertBST(TreeNode* root) {
// Write your code here
add(root);
return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: