给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
思路一:递归
不能单纯判断当前节点与左右的大小,比如
5
4 6
3 7
这个3比4小,是不可以的。所以:
- 对于左节点,当前节点及之后节点的最大值是他的父节点;
- 对于右节点,当前节点及之后节点的最小值是他的父节点;
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def dfs(root,minval,maxval):
if not root:
return True
if root.val>minval and root.val<maxval:
pass#循环中才能continue
else:
return False
if not dfs(root.left,minval,root.val):
return False
if not dfs(root.right,root.val,maxval):
return False
return True
return dfs(root,-math.inf,math.inf)
思路二:中序遍历
若中序遍历的结果是严格递增的,则符合题意,用n记录前一个数的大小
中序遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack=[]
n=-math.inf
while stack or root:
if root:
stack.append(root)
root=root.left
else:
temp=stack.pop()
if temp.val<=n:
return False
n=temp.val
root=temp.right
return True