检查一棵二叉树是否为二叉查找树

来源:互联网 发布:神奇软件 编辑:程序博客网 时间:2024/05/29 12:24

惊恐题目:实现一个函数,检查一棵二叉树是否为二叉查找树。


public static int index=0;
public static copyBST(TreeNode root,int [] array)
{
if(root== null) return ;
copyBST(root.left,array);
array[index]=root.data;
index++;
copyBST(root.right,array);
}
public static boolean checkBST(TreeNode root)
{
int [] array=new int[root.size];
copyBST(root,array);
for(int i=1;i<array.length;i++)
{
if(array[i]<=array[i-1]) return false;
}
return true;
}


public static int last_printed=Integer.MIN_VALUE;
public static boolean checkBST(TreeNode n)
{
if(n==null) return true;
//递归检查左子树
if(!checkBST(n.left)) return false;
//检查当前结点
if(n.data<=last_printed) return false;
last_printed=n.data;
//递归检查右子树
if(!checkBST(n.right)) return false;
return true;//全部检查完毕
}



惊恐解法二:最小/最大法



boolean checkBST(TreeNode n)
{
     return checkBST(n,Integer.MIN_VALUE,Integer.MAX_VALUE);
}
boolean checkBST(TreeNode n,int min,int max)
{
if(n==null)
return true;
if(n.data<min||n.data>max)
return false;
if(!checkBST(n.left,min,n.data)||!checkBST(n.right,n.data,max));
{
return false;
}
return true;
}


0 0
原创粉丝点击