题目:
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
解答:
方法一:递归
(1)按中序遍历,使用cur_max不断更新最大值,当无法更新时返回False.
# 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:
cur_max = -float("INF")
def traversal(root):
nonlocal cur_max
if not root:
return True
lv=traversal(root.left)
#print("before:",cur_max,root.val)
if root.val>cur_max:
cur_max=root.val
else:
return False
#print("after:",cur_max,root.val)
rv=traversal(root.right)
return lv and rv
return traversal(root)
(2)中序遍历,转换成数组后再判别
# 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 traversal(cur,res):
if not cur:
return
if cur.left:
traversal(cur.left,res)
res.append(cur.val)
if cur.right:
traversal(cur.right,res)
res=[]
traversal(root,res)
n=len(res)
for i in range(1,n):
if res[i-1]>=res[i]:
return False
return True
方法二:迭代
(1)中序遍历-一般写法
# 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=[]
pre,cur=None,root
while cur or stack:
#访问到最左节点
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
(2)中序遍历-统一写法
# 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:
#中序遍历
pre=None
stack=[root]
while stack:
cur=stack[-1]
if cur:
cur=stack.pop()
if cur.right: #右
stack.append(cur.right)
stack.append(cur) #根
stack.append(None)
if cur.left: #左
stack.append(cur.left)
else:
stack.pop() #弹出空节点
cur=stack.pop() #处理当前节点
if pre and pre.val>=cur.val:
return False
pre=cur
return True