Convert BST to Greater Tree
2017-05-21 09:40
295 查看
问题描述: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
题目大意:给定一棵二叉查找树,将其转化为“Greater Tree”,原始BST中的每一个节点都替换为不小于其本身的各节点的和。
实现思路:树的最右边的节点的值不变,其根节点的值等于根节点加上右子树的值之和,左子树的值等于左子树的数值加上上一步得到的根节点的数值,按照这个规则将二叉树的所有节点的值替换一遍。逆序遍历,先遍历右子树,处理当前节点,再遍历左子树。
实现代码:/**
* 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 travel(TreeNode* root)
{
if(root==NULL)
return;
travel(root->right);
sum+=(root->val);
root->val=sum;
travel(root->left);
}
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL)
return NULL;
travel(root);
return root;
}
};
做题感想:一看到二叉排序树,直接可以想到中序遍历,这个题和普通中序遍历不同的地方在于,它要把整棵树中比自己大的节点加起来。
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
题目大意:给定一棵二叉查找树,将其转化为“Greater Tree”,原始BST中的每一个节点都替换为不小于其本身的各节点的和。
实现思路:树的最右边的节点的值不变,其根节点的值等于根节点加上右子树的值之和,左子树的值等于左子树的数值加上上一步得到的根节点的数值,按照这个规则将二叉树的所有节点的值替换一遍。逆序遍历,先遍历右子树,处理当前节点,再遍历左子树。
实现代码:/**
* 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 travel(TreeNode* root)
{
if(root==NULL)
return;
travel(root->right);
sum+=(root->val);
root->val=sum;
travel(root->left);
}
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL)
return NULL;
travel(root);
return root;
}
};
做题感想:一看到二叉排序树,直接可以想到中序遍历,这个题和普通中序遍历不同的地方在于,它要把整棵树中比自己大的节点加起来。
相关文章推荐
- Convert BST to Greater Tree(leetcode)
- LeetCode Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- leetcode 538 Convert BST to Greater Tree C++
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- LeetCode: Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Leetcode | Convert BST to Greater Tree
- 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