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 is binary search trees.
By definition Http://en.wikipedia.org/wiki/Binary_search_tree
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.
The left and right subtree each must also is a binary search tree.
Each node can has up to successor nodes.
There must be no duplicate nodes.
A unique path exists from the root to every and other node.
The left dial hand tree is smaller than the node is less than the right subtree and cannot have duplicate values. The practice is that we compare the values of the left and right nodes each time, and return False if one of the nodes does not meet the criteria
We compare the left and right node key with root key. If any of the condition cannot match the requirement, we return False.
# Definition for a binary tree node# class treenode:# def __init__ (self, x): # self.val = x# self.left = No ne# self.right = Noneclass solution: # @param root, a tree node # @return A Boolean def testnode (self,root , minval,maxval): if Root==none: return True if Root.val>maxval or root.val<minval: return False return Self.testnode (ROOT.LEFT,MINVAL,ROOT.VAL-1) and Self.testnode (Root.right,root.val+1,maxval) def isvalidbst (self, root): minval=-3147483648 maxval=3147483648 return Self.testnode (Root, Minval,maxval)
Validate Binary Search Tree leetcode Python