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.
判断一颗二叉树是不是二叉查找树~ 跟上一题相似,可以利用BST的中序遍历是有序的这一性质来做~可以根据中序遍历的非递归解法,然后保存前驱结点pre,比较前驱结点pre和当前节点cur的值,判断是否满足递增关系,如果不满足,直接返回False~代码如下~
class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
if root is None: return True
stack, pre, cur = [], None, root
while stack or cur:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
if pre and pre.val >= cur.val:
return False
pre, cur = cur, cur.right
return True
网上还有一种解法: 就是对于每个结点保存左右界,也就是保证结点满足它的左子树的每个结点比当前结点值小,右子树的每个结点比当前结点值大。对于根节点不用定位界,所以是无穷小到无穷大,接下来当我们往左边走时,上界就变成当前结点的值,下界不变,而往右边走时,下界则变成当前结点值,上界不变。如果在递归中遇到结点值超越了自己的上下界,则返回false,否则返回左右子树的结果
class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
return self.isValidBSTRecur(root, 9223372036854775807, -9223372036854775808)
def isValidBSTRecur(self, root, upper, lower):
if root is None: return True
if root.val <= lower or root.val >= upper:
return False
return self.isValidBSTRecur(root.left, root.val, lower) and self.isValidBSTRecur(root.right, upper, root.val)