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:
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
这一题我没理解BST的性质,然后就写了个对于普遍树的解法,发现只beat了0.88%的人也是蛮心酸的。
public class Convert_BST_to_Greater_Tree_538 {
int length=0;
int pointer=0;
void getAllNums(TreeNode root,int[] nums){
if(root==null){
return ;
}
nums[length]=root.val;
length++;
getAllNums(root.left,nums);
getAllNums(root.right,nums);
}
void setNums(TreeNode root,int[] addNums){
if(root==null){
return ;
}
root.val+=addNums[pointer];
pointer++;
setNums(root.left, addNums);
setNums(root.right, addNums);
}
public TreeNode convertBST(TreeNode root) {
int[] nums=new int[10000];
getAllNums(root, nums);
int[] addNums=new int[length];
for(int i=0;i<length;i++){
int theValue=nums[i];
for(int j=0;j<length;j++){
if(j!=i){
if(nums[j]>theValue){
addNums[i]+=nums[j];
}
}
}
}
setNums(root,addNums);
return root;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Convert_BST_to_Greater_Tree_538 c=new Convert_BST_to_Greater_Tree_538();
TreeNode root=new TreeNode(5);
root.left=new TreeNode(2);
root.right=new TreeNode(13);
c.convertBST(root);
}
}
BST树的性质就是一个结点的值肯定大于它的左结点,小于它的右结点。
二叉查找树(Binary Search Tree),是指一棵空树或者具有下列性质的二叉树:
1.若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
2.任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
3.任意节点的左、右子树也分别为二叉查找树。
4.没有键值相等的节点(no duplicate nodes)。
有了这个性质之后,直接用 右-根-左 的顺序遍历就好了。
public class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null) return null;
convertBST(root.right);
root.val += sum;
sum = root.val;
convertBST(root.left);
return root;
}
}
Idea: Reversely traverse the tree and keep a sum of all previously visited values. Because its a BST, values seen before are all greater than current node.val.