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,13}:
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 n=0;
bianli(root,n);
return root;
}
void bianli(TreeNode* root,int &n)
{if(root==NULL) return;
bianli(root->right,n);
root->val=root->val+n;
n=root->val;
bianli(root->left,n);
}
};
4、感想
右子树=13,根节点=5+13=18,左子树=2+18,进行反的中序遍历,最右边的节点不变,根节点加右子树的值,左子树加转化后的根节点的值,最后的二叉树实际与二叉排序树相反。