538. Convert BST to Greater Tree
2017-06-18 12:46
471 查看
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.
Example:
Subscribe to see which companies asked this question.
将搜索二叉树按节点的值从大到小累加。累加过程中,累加的值存在节点中。这种按顺序的操作联想到了中序遍历,可以看做是从后向前的中序遍历。
代码:
class Solution
{
public:
TreeNode* convertBST(TreeNode* root)
{
inorder(root);
return root;
}
private:
void inorder(TreeNode* root)
{
if(root)
{
inorder(root->right);
root->val += sum;
sum = root->val;
inorder(root->left);
}
}
int sum = 0;
};
Example:
Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13
Subscribe to see which companies asked this question.
将搜索二叉树按节点的值从大到小累加。累加过程中,累加的值存在节点中。这种按顺序的操作联想到了中序遍历,可以看做是从后向前的中序遍历。
代码:
class Solution
{
public:
TreeNode* convertBST(TreeNode* root)
{
inorder(root);
return root;
}
private:
void inorder(TreeNode* root)
{
if(root)
{
inorder(root->right);
root->val += sum;
sum = root->val;
inorder(root->left);
}
}
int sum = 0;
};
相关文章推荐
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- leetcode 538 Convert BST to Greater Tree C++
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- [538 Convert BST to Greater Tree]搜索二叉树的数值计算
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- LeetCode 538 Convert BST to Greater Tree(二叉树的右中左遍历)
- 538. Convert BST to Greater Tree
- LeetCode 538----Convert BST to Greater Tree
- Leetcode 538:Convert BST to Greater Tree
- LeetCode-538 Convert BST to Greater Tree
- leetcode(538). Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree