654. 最大二叉树
递归:
递归传数组会超时,只能建辅助函数传数组的边界值。
递归终止条件:传入的数组为空——左边界大于等于右边界,节点为None
递归过程:找到最大值,创建节点,计算在原数组中的索引用于处理下一轮传入的边界。递归地连接左子树,递归地连接右子树。
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def construct(start,end):
if start >= end:
return None
root_val = max(nums[start:end])
max_idx = nums.index(root_val,start,end)
root = TreeNode(root_val)
root.left = construct(start, max_idx)
root.right = construct(max_idx + 1, end)
return root
return construct(0, len(nums))
单调栈:
创一个单调递减栈,遍历数组,找右边第一个比当前值大的元素。找到比栈顶大的元素后,一直弹出栈内元素,直到空栈或者栈顶元素比当前值大,每次弹出,弹出元素设为当前节点的左子节点,这样,弹完后当前节点的左指针指向当前数组中它左边的最大值;每次只要栈不为空,栈顶元素的右指针指向当前元素,因为左边第一个比他大的元素就是它的父节点。
class Solution:
def constructMaximumBinaryTree(self,nums):
stack = []
for num in nums:
curr_node = TreeNode(num)
while stack and stack[-1].val < num:
curr_node.left = stack.pop()
if stack:
stack[-1].right = curr_node
stack.append(curr_node)
return stack[0]
617. 合并二叉树
递归:
如果root1为空,直接返回root2,因为root1已经是空了,也就不会有子树了..看起来很容易但是没有想到这一点。
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1: return root2
if not root2: return root1
root = TreeNode(root1.val+root2.val)
root.left = self.mergeTrees(root1.left,root2.left)
root.right = self.mergeTrees(root1.right,root2.right)
return root
迭代:
from collections import deque
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if not root1:
return root2
if not root2:
return root1
queue = deque()
queue.append((root1, root2))
while queue:
node1, node2 = queue.popleft()
node1.val += node2.val
if node1.left and node2.left:
queue.append((node1.left, node2.left))
elif not node1.left:
node1.left = node2.left
if node1.right and node2.right:
queue.append((node1.right, node2.right))
elif not node1.right:
node1.right = node2.right
return root1
700. 二叉搜索树中的搜索
二叉搜索树:每个节点都满足当前节点比左子树所有节点大比右子树所有节点小的树。
迭代:
这不是二分查找?
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root:
if val == root.val: return root
elif val > root.val:
root = root.right
else:
root = root.left
return None
递归:
这还能递归?
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root or root.val == val:
return root
return self.searchBST(root.left,val) or self.searchBST(root.right, val)
98. 验证二叉搜索树
递归一:
创建辅助函数,传入当前允许的最大值和最小值,初始化为正负无穷大。终止条件是空节点,直接返回True因为最后是and运算符,遇到不符合最大最小值限制的,返回False。递归地查看左右子树是否满足二叉搜索树的要求,左子树的最大值更新为当前节点值,右子树的最小值更新为当前节点值。
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def helper(root, maxVal = float('inf'), minVal = float('-inf')):
if not root:
return True
if not (minVal < root.val < maxVal):
return False
return helper(root.left, root.val, minVal) and helper(root.right, maxVal, root.val)
return helper(root)
递归二:
注意到BST的中序遍历是递增的
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
nums = []
def travesal(root):
if not root:
return
travesal(root.left)
nums.append(root.val)
travesal(root.right)
travesal(root)
for i in range(1, len(nums)):
if nums[i] <= nums[i - 1]:
return False
return True
迭代:
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
stack = []
minVal = float('-inf')
cur = root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if minVal < cur.val:
minVal = cur.val
else:
return False
cur = cur.right
return True
文章介绍了如何使用递归和非递归方法构建最大二叉树、合并两个二叉树以及在二叉搜索树中搜索和验证其结构。涉及递归终止条件、辅助函数、单调栈和迭代算法的应用。

被折叠的 条评论
为什么被折叠?



