题目:Given a binary tree, determine if it is a valid binary search tree (BST).
二叉搜索树判定:左子树上的结点的值都比父节点小,右子树都比父节点大。且左右子树也分别为二叉搜索树。
方法一:利用BST性质,中序遍历为递增序列。
import java.util.*;
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null)
return true;
ArrayList<Integer> list=new ArrayList();
inOrder(root,list);
for(int i=0;i<list.size()-1;i++)
{
if(list.get(i)>=list.get(i+1))
{
return false;
}
}
return true;
}
public void inOrder(TreeNode root,ArrayList<Integer> list)
{
if(root == null)
return;
inOrder(root.left,list);
list.add(root.val);
inOrder(root.right,list);
}
}
不需要辅助空间的中序遍历版本。
public class Solution {
private TreeNode pre=null;
public boolean isValidBST(TreeNode root) {
if(root == null)
return true;
if(!isValidBST(root.left))
return false;
if(pre!=null&&pre.val>=root.val)
return false;
pre=root;//记录inorder的上一个结点;
return isValidBST(root.right);
}
}