Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
soulution:
如果是左子树,限制条件就是最大的不能超过父节点,如果是右子树,限制条件就是最小不能超过父节点。
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root==null)return true;
return helper(root.left,root.val,Long.MIN_VALUE) && helper(root.right,Long.MAX_VALUE,root.val);
}
boolean helper(TreeNode p,long max,long min){
if(p==null)return true;
if(p.val>=max || p.val<=min)return false;
return helper(p.left,p.val,min) && helper(p.right,max,p.val);
}
}