题目描述
请实现一个函数,检查一棵二叉树是否为二叉查找树。
给定树的根结点指针TreeNode* root,请返回一个bool,代表该树是否为二叉查找树。
思路:
.已知中序遍历排序二叉查找树,得到的序列应是有序的。所以只要比较中序遍历的前一项和当前项就可以了。
方法一:
public boolean checkBST(TreeNode root) {
int min = 0;
return inorder(root,min);
}
private boolean inorder(TreeNode root,int last) {
if (root == null) {
return true;
}
if (!(inorder(root.left,last)))
return false;
if (root.value<last)
return false;
last = root.value;
if(!( inorder(root.right,last)))
return false;
return true;
}
方法二:
public boolean checkBST(TreeNode root) {
// write code here
if(root == null || (root.left == null && root.right == null)){
return true;
}
boolean leftIsBST = true, rightIsBST = true;
if(root.left != null && root.left.val <= root.val){
leftIsBST = checkBST(root.left);
}else if(root.left != null && root.left.val > root.val){
leftIsBST = false;
}else{}// root.left == null
if(root.right != null && root.right.val >= root.val){
rightIsBST = checkBST(root.right);
}else if(root.right != null && root.right.val < root.val){
rightIsBST = false;
}else{}
return leftIsBST && rightIsBST;
}