241 words
1 minute
日拱两卒(七)
2026-08-02
40
二叉树的直径。
这里的坑是长度是按边计算的,不是节点数。
class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: ans = 0
def dfs(cur) -> int: nonlocal ans if cur is None: return 0 l = dfs(cur.left) + 1 r = dfs(cur.right) + 1 nonlocal ans ans = max(ans, l + r - 2) return max(l, r)
dfs(root) return ans39
对称二叉树。
不能拍成中序遍历看回文,是有反例的。
class Solution: def isSame(self, p, q) -> bool: if p is None or q is None: return p is q if p.val != q.val: return False return self.isSame(p.left, q.right) and self.isSame(p.right, q.left)
def isSymmetric(self, root: Optional[TreeNode]) -> bool: return self.isSame(root.left, root.right)38
翻转二叉树。
简单递归。
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None tmp = deepcopy(root.right) root.right = self.invertTree(root.left) root.left = self.invertTree(tmp) return root37
二叉树的最大深度。
简单递归。
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)36
二叉树的中序遍历。
简单递归。
class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: ans = []
def dfs(cur): if cur is None: return dfs(cur.left) ans.append(cur.val) dfs(cur.right)
dfs(root)
return ans