lintcode_Convert BST to Greater Tree
2017-05-21 23:17
281 查看
1.描述:
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.
您在真实的面试中是否遇到过这个题?
Yes
样例
Given a binary search Tree `{5,2,3}`:
Return the root of new tree
2.思路:
先找到最右节点,从右往左依次更新节点值即可
3.代码:
int rr=0;
TreeNode* convertBST(TreeNode* root) {
if(root==NULL) return NULL;
else {
convertBST(root->right);
root->val+=rr;
rr=root->val;
convertBST(root->left);
}
return root;
}
4.感想:
这个题一开始想复杂了,总想着先去遍历一遍记录所有节点值,结果越走越远
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.
您在真实的面试中是否遇到过这个题?
Yes
样例
Given a binary search Tree `{5,2,3}`:
5 / \ 2 13
Return the root of new tree
18 / \ 20 13
2.思路:
先找到最右节点,从右往左依次更新节点值即可
3.代码:
int rr=0;
TreeNode* convertBST(TreeNode* root) {
if(root==NULL) return NULL;
else {
convertBST(root->right);
root->val+=rr;
rr=root->val;
convertBST(root->left);
}
return root;
}
4.感想:
这个题一开始想复杂了,总想着先去遍历一遍记录所有节点值,结果越走越远
相关文章推荐
- Convert BST to Greater Tree-LintCode
- lintcode(661)Convert BST to Greater Tree
- lintcode——Convert BST to Greater Tree
- Convert BST to Greater Tree(leetcode)
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 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
- LeetCode - 538 - Convert BST to Greater Tree
- leetcode[Convert BST to Greater Tree]//待整理多种解法
- leetcode(538). Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- lintcode Convert BST to Greater Tree