classSolution: defverticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: g = [[] for _ inrange(30)] q = deque([(root, 15)]) while q: sz = len(q) temp = [] for _ inrange(sz): poll = q.popleft() temp.append((poll[1], poll[0].val)) if poll[0].left: q.append((poll[0].left, poll[1] - 1)) if poll[0].right: q.append((poll[0].right, poll[1] + 1)) temp.sort() for e in temp: g[e[0]].append(e[1])
ret = [] for e in g: iflen(e) != 0: ret.append(e) return ret
输出[9, 3, 15, 20, 7]
层序遍历(递归)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: deflevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ifnot root: return [] g = [[] for _ inrange(2000)]
defdfs(r: 'TreeNode', t: int) -> None: g[t].append(r.val) if r.left: dfs(r.left, t + 1) # 根据递归的思路,这样写也是符合顺序的 if r.right: dfs(r.right, t + 1)
dfs(root, 0) ret = [] for e in g: iflen(e): ret.append(e) return ret
前中恢复二叉树
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defbuildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: n = len(preorder) d = {val: idx for idx, val inenumerate(inorder)}
defdfs(pl: int, pr: int, il: int, ir: int) -> Optional[TreeNode]: if pl > pr or il > ir: returnNone node = TreeNode(preorder[pl]) t = d[preorder[pl]] node.left = dfs(pl + 1, pl + t - il, il, t - 1) node.right = dfs(pl + t - il + 1, pr, t + 1, ir) return node
return dfs(0, n - 1, 0, n - 1)
中后恢复二叉树
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defbuildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: n = len(inorder) d = {val: idx for idx, val inenumerate(inorder)}
defdfs(pl: int, pr: int, il: int, ir: int) -> Optional[TreeNode]: if pl > pr or il > ir: returnNone node = TreeNode(postorder[pr]) t = d[postorder[pr]] node.left = dfs(pl, pr - ir + t - 1, il, t - 1) node.right = dfs(pr - ir + t, pr - 1, t + 1, ir) return node
return dfs(0, n - 1, 0, n - 1)
前后恢复二叉树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 前序遍历和后续遍历不能确定一颗二叉树 classSolution: def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: n = len(pre) d = {val: idx for idx, val in enumerate(post)}
def dfs(prl: int, prr: int, pol: int, por: int) -> TreeNode: if prl > prr: return node= TreeNode(pre[prl]) if prl == prr: returnnode nxt= prl + 1 t = d[pre[nxt]] - pol node.left = dfs(nxt, nxt + t, pol, pol + t) node.right = dfs(nxt + t + 1, prr, pol + t + 1, por - 1) return node