题解 | #判断一棵二叉树是否为搜索二叉树和完全二叉树# 一次递归遍历同时判断
判断一棵二叉树是否为搜索二叉树和完全二叉树
http://www.nowcoder.com/practice/f31fc6d3caf24e7f8b4deb5cd9b5fa97
非常直观的代码,直接看代码就能懂
class Solution:
def judgeIt(self , root: TreeNode) -> List[bool]:
from dataclasses import dataclass
@dataclass
class Info:
mx: int # 整棵树的最大值
mi: int # 整棵树的最小值
height: int # 树的高度
is_bst: bool # 是否搜索二叉树
is_full: bool # 是否满二叉树
is_cbt: bool # 是否完全二叉树
def dfs(x):
if not x: return Info(float('-inf'), float('inf'), 0, True, True, True)
l, r = dfs(x.left), dfs(x.right)
# 使用左右子树的信息得到当前节点的信息
mx = max(x.val, r.mx)
mi = min(x.val, l.mi)
height = max(l.height, r.height) + 1
is_bst = l.is_bst and r.is_bst and l.mx < x.val < r.mi
is_full = l.is_full and r.is_full and l.height == r.height
is_cbt = is_full or \
l.is_full and r.is_full and l.height - 1 == r.height or \
l.is_full and r.is_cbt and l.height == r.height or \
l.is_cbt and r.is_full and l.height - 1 == r.height
return Info(mx, mi, height, is_bst, is_full, is_cbt)
info = dfs(root)
return info.is_bst, info.is_cbt