Leetcode[98] Validate Binary Search Tree
07 Nov 2015###Task1 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.
###Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
maxEle = (1 << 63) - 1
minEle = (-1) << 63
return self.isValid(root, maxEle, minEle)
def isValid(self, root, maxEle, minEle):
if root == None:
return True
if root.val <= minEle or root.val >= maxEle:
return False
return self.isValid(root.left, root.val, minEle) and self.isValid(root.right, maxEle, root.val)
###Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean helper(TreeNode root, double min, double max) {
if (root == null) {
return true;
}
if (root.val <= min || root.val >= max) {
return false;
}
return (helper(root.left, min, root.val) && helper(root.right, root.val, max));
}
public boolean isValidBST(TreeNode root) {
return helper(root, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
}
###Points
- Divide and conquer, maintain max&min with recursion
- Recursive end: reach None node
- Python’s way: maxEle = (1 « 63) - 1 minEle = (-1) « 63