leetcode 538. Convert BST to Greater Tree

257 篇文章 17 订阅

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. 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值