386 字
2 分钟
代码随想录算法训练营第十二天 | 二叉树 Part02
226. 翻转二叉树
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return root # 交换当前节点的左右子树 root.left, root.right = root.right, root.left # 递归翻转左子树 self.invertTree(root.left) # 递归翻转右子树 self.invertTree(root.right) return root
101. 对称二叉树
class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: if not root: return True return self.compare(root.left, root.right)
def compare(self, left: Optional[TreeNode], right: Optional[TreeNode]) -> bool: # 检查左右子树是否对称 if left is None and right is not None: return False elif left is not None and right is None: return False elif left is None and right is None: return True elif left.val != right.val: return False # 递归比较外侧和内侧的节点是否对称 outside = self.compare(left.left, right.right) inside = self.compare(left.right, right.left) return outside and inside
104. 二叉树的最大深度
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: res = 0 if not root: return res q = deque([root]) # 使用队列进行层序遍历 while q: size = len(q) res += 1 # 每遍历一层,深度 +1 for _ in range(size): cur = q.popleft() if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) return res
111. 二叉树的最小深度
class Solution: # 根节点到最近的叶子节点的最小深度 def minDepth(self, root: Optional[TreeNode]) -> int: res = 0 if not root: return res q = deque([root]) while q: size = len(q) res += 1 # 每进入一层,深度加一 for _ in range(size): cur = q.popleft() # 如果当前节点是叶子节点,返回当前深度 if not cur.left and not cur.right: return res if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) return res
代码随想录算法训练营第十二天 | 二叉树 Part02
https://fuwari.vercel.app/posts/code_musings_day_twelve/