Build BST using Preorder sequence and Verify valid BST

public class BuildBSTPreorder {
     public class TreeNode{
    	 TreeNode left;
    	 TreeNode right;
    	 int val;
    	 TreeNode(int x){
    		 this.val = x;
    	 }
     }
     
     public TreeNode buildBST(int[] num){
    	 if(num.length <=0) return null;
    	 int[] index = new int[]{0};
     	 return build(num,num.length,Integer.MIN_VALUE, Integer.MAX_VALUE,index);
     }
     
     public TreeNode build(int[] num,int length,int min, int max, int[] index ){
    	 if(num.length>=length){
    		 return null;
    	 }
    	 TreeNode node = null;
    	 int current = num[index[0]];
    	 if( min<current && current<max){
    		 node = new TreeNode(current);
    		 index[0]++;
    		 
    		 if(index[0]<length){
    			 node.left = build(num,length,min,current,index);
    			 node.right = build(num,length,current,max,index);
    		 }
    	 }
    	 return node;
     }
     
     public boolean isValidBST(TreeNode root){
    	 if(root == null) return true;
    	 TreeNode[] pre = new TreeNode[1];
    	 return isvalid(root,pre);
     }
     
     public boolean isvalid(TreeNode root, TreeNode[] pre){
    	 if(root == null) return true;
    	 if(!isvalid(root.left,pre)){
    		 return false;
    	 }
    	 
    	 if(pre[0]!=null){
    		 if(root.val<=pre[0].val){
    			 return false;
    		 }
    	 }
    	 pre[0] = root;
    	 if(!isvalid(root.right,pre)){
    		 return false;
    	 }
    	 return true;
     }
	 
	public static void main(String[] args) {
		BuildBSTPreorder solution = new BuildBSTPreorder();
		int[] num = {2,1,3};
		TreeNode node = solution.buildBST(num);
        boolean flag = solution.isValidBST(node);
        if(flag == true){
        	System.out.println("YES");
        }else{
        	System.out.println("NO");
        }
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值