题目
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.
Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
思路
思路1: 用递归,每次判断 root-left 和root-right的大小,然后给左子树和右子树设一个取值范围。用递归判断子树是否为二叉搜索树。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidSub(self,root,base_left,base_right):
if root.left:
if root.left.val >= root.val or root.left.val <= base_left:
return False
if not self.isValidSub(root.left,base_left,root.val):
return False
if root.right:
if root.right.val <= root.val or root.right.val >=base_right:
return False
if not self.isValidSub(root.right,root.val,base_right):
return False
return True
def isValidBST(self, root: TreeNode) -> bool:
if root == None:
return True
return self.isValidSub(root,-sys.maxsize,sys.maxsize)
思路二:
用栈,按照 left-root-right的顺序遍历树,如果遍历到的数字要比前一个数字小,则返回 False。如果遍历完都正常,则返回True
def isValidBST(self, root: TreeNode) -> bool:
if root == None:
return True
stack_root = []
nums = [-sys.maxsize]
while(1):
while(1):
while root.left:
if root.left.val >= root.val:
return False
stack_root.append(root)
root = root.left
if root.val <= nums[-1]:
return False
nums.append(root.val)
if root.right:
if root.right.val <= root.val:
return False
root = root.right
else:
break
if len(stack_root)>0:
root = stack_root.pop()
if root.val <= nums[-1]:
return False
nums.append(root.val)
while (root.right == None) and len(stack_root)>0:
root = stack_root.pop()
if root.val <= nums[-1]:
return False
nums.append(root.val)
if root.right:
root = root.right
else:
break
else:
break
return True