判断一棵树是否为搜索二叉树
搜索二叉树的特点是当前节点的值大于左子树的值,小于右子树的值。即中序遍历的结果为升序。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null) return true;
Stack<TreeNode> s = new Stack<>();
long min = Long.MIN_VALUE;//这里要使用一个long来记录最小的数,防止错误。
while(root != null || !s.isEmpty()){
if(root != null){
s.add(root);
root = root.left;
}else{
root = s.pop();
if(min >= root.val)
return false;
min = root.val;
root = root.right;
}
}
return true;
}
}