合法二叉搜索树验证
实现一个函数,检查一棵二叉树是否为二叉搜索树。
方法一
- 定义small保存该节点的最近右父节点,要大于该值
- 定义large保存该节点的最近左父节点,要小于该值
class Solution {
public boolean isValidBST(TreeNode root) {
return judge(root, null, null);
}
public boolean judge(TreeNode root, Integer small, Integer large){
if (root == null){
return true;
}
int val = root.val;
if (small != null && val <= small){
return false;
}
if (large != null && val >= large){
return false;
}
if (!judge(root.left, small, val)){
return false;
}
if (!judge(root.right, val, large)){
return false;
}
return true;
}
}
方法二:使用中序遍历
class Solution {
Queue<Integer> list = new LinkedList<>();
int temp;
public boolean isValidBST(TreeNode root) {
while(list.size()>1){
temp = list.poll();
if (temp >= list.peek()){
return false;
}
}
if (root == null){
return true;
}
boolean left = isValidBST(root.left);
list.add(root.val);
boolean right =isValidBST(root.right);
return left && right;
}
}