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}`:
Return the root of new tree
思路:
基于二叉排序树的性质,即根节点的左子树上的节点都小于根节点,右子树上的节点都大于根结点。
所以这个题就需要从最右边的叶子节点开始访问,因为它是整棵树中最大的节点,访问顺序为 右子树->根节点->左子树。
在访问一个节点时依序加上之前访问过的节点,谁让那些节点都比它大呢!
AC代码:
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; } };
相关文章推荐
- lintcode——Convert BST to Greater Tree
- lintcode(661)Convert BST to Greater Tree
- lintcode_Convert BST to Greater Tree
- LeetCode Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- LC-Convert BST to Greater Tree
- Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- convert bst to greater tree
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 661.Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree