描述
给定二叉搜索树(BST),将其转换为更大的树,使原始BST上每个节点的值都更改为在原始树中大于等于该节点值的节点值之和(包括该节点)。
样例
Given a binary search Tree `{5,2,13}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
代码
根据二叉查找树的特点和题意,可以想到,从右子树开始中序遍历,同时求出节点值的和,并把和赋给当前的节点值。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of binary tree
* @return: the new root
*/
int sum=0;
public TreeNode convertBST(TreeNode root) {
// write your code here
if(root==null){
return null;
}
root.right=convertBST(root.right);
sum+=root.val;
root.val=sum;
root.left=convertBST(root.left);
return root;
}
}