写在前面
本篇全部集中在二叉树相关问题上,是参考东哥的思路进行的练习和思考。东哥有《labuladong 的算法小抄》以及宝藏微信公众号 labuladong,github 也有项目,自来水推荐购买和关注。
二叉树思考学习记录
Day6 二叉搜索树加强
Day6 练习
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
if not root: return 0
res = 0
if low <= root.val <= high:
res += root.val
elif root.val < low:
res += self.rangeSumBST(root.right, low, high)
return res
elif root.val > high:
res += self.rangeSumBST(root.left, low, high)
return res
res += self.rangeSumBST(root.left, low, high)
res += self.rangeSumBST(root.right, low, high)
return res
def isValidBST(self, root: TreeNode) -> bool:
def check(root, min_node, max_node):
if not root: return True
if min_node and root.val <= min_node.val: return False
if max_node and root.val >= max_node.val: return False
return check(root.left, min_node, root) and check(root.right, root, max_node)
return check(root, None, None)
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
if not root: return None
if root.val < low:
return self.trimBST(root.right, low, high)
elif root.val > high:
return self.trimBST(root.left, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
self.push_all_left(root)
def push_all_left(self, root):
while root :
self.stack.append(root)
root = root.left
def next(self) -> int:
last_node = self.stack.pop()
self.push_all_left(last_node.right)
return last_node.val
def hasNext(self) -> bool:
return len(self.stack) != 0
附加题目:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.stack = []
def push_all_left(root):
while root:
self.stack.append(root)
root = root.left
return
push_all_left(root)
while k:
last_node = self.stack.pop()
k -= 1
push_all_left(last_node.right)
return last_node.val
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
def build(start, end):
if start > end: return None
root = TreeNode(preorder[start])
left_size = 0
for i in range(start + 1, end + 1):
if preorder[i] < root.val:
left_size += 1
else:
break
root.left = build(start + 1, start + left_size)
root.right = build(start + left_size + 1, end)
return root
return build(0, len(preorder) - 1)
|