Convert BST to Greater Tree
2017-05-18 17:05
591 查看
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.
Given a binary search Tree `{5,2,3}`:
Return the root of new tree
2.解题思路
定义一个求和的新的函数,进行后序遍历的时候进行累加求和,以此将当前的累加和与当前节点相加赋给当前节点。
3.代码实现
/**
* 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
*/
TreeNode* convertBST(TreeNode* root) {
// Write your code here
int sum;
SUM(root,sum);
return root;
}
void SUM(TreeNode*root,int &sum)
{
if(root==NULL)
return ;
else{
SUM(root->right,sum);
root->val+=sum;
sum=root->val;
SUM(root->left,sum);
}
}
};
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.
Given a binary search Tree `{5,2,3}`:
5 / \ 2 13
Return the root of new tree
18 / \ 20 13
2.解题思路
定义一个求和的新的函数,进行后序遍历的时候进行累加求和,以此将当前的累加和与当前节点相加赋给当前节点。
3.代码实现
/**
* 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
*/
TreeNode* convertBST(TreeNode* root) {
// Write your code here
int sum;
SUM(root,sum);
return root;
}
void SUM(TreeNode*root,int &sum)
{
if(root==NULL)
return ;
else{
SUM(root->right,sum);
root->val+=sum;
sum=root->val;
SUM(root->left,sum);
}
}
};
4.感想
本题是将节点值比当前节点大的节点都加到当前节点,所以递归的时候按后序遍历求和。
相关文章推荐
- 538. Convert BST to Greater Tree
- LintCode 661 Convert BST to Greater Tree
- 661.Convert BST to Greater Tree
- 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
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- LintCode Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- LeetCode 538 Convert BST to Greater Tree(二叉树的右中左遍历)
- LeetCode之Convert BST to Greater Tree(Kotlin)
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Leetcode 538:Convert BST to Greater Tree
- [LeetCode] Convert BST to Greater Tree 将二叉搜索树BST转为较大树
- Convert BST to Greater Tree
- LintCode-Convert BST to Greater Tree