The idea is to find the min and max for the current node, if qualify, verify its left and right with updated min and max… The tough part is to remember to pass node, and min and max and update… remember!!!
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
//return isBSTValid(root.left, Integer.MIN_VALUE, root.val) && isBSTValid(root.right, root.val, Integer.MAX_VALUE);
return isBSTValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean isBSTValid(TreeNode node, int minValue, int maxValue){
if(node == null){
return true;
}
if(node.val >= maxValue || node.val <= minValue){
return false;
}else{
return isBSTValid(node.left, minValue, node.val) && isBSTValid(node.right, node.val, maxValue);
}
}
}
没有评论:
发表评论