二叉树算法总结
几种遍历算法:
- Pre-Order 前序:
- 生成一条搜索路径。因为父节点永远先被操作。
- 第一次访问就输出数据。
- 可以用来实现目录结构的展示。
- In-Order 中序:
- (二叉树)特点是遍历顺序从小到大:要求排序的情形。
- 中缀表达式。
- Post-Order 后序:
- 在执行操作时,已经遍历过该节点的子节点:进行破坏性操作:比如删除节点。
- 目录文件大小计算。
- 后缀表达式。
- BFS 广度优先:
- 层序遍历。
- 最短路径。
- 树很高。
- DFS 深度优先:
- 树很胖。
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res, stack = [], [(root, False)]
while stack:
node, visited = stack.pop() # the last element
if node:
if visited:
res.append(node.val)
else: # postorder: left -> right -> root
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
return res
参考:
插入/删除
Insertion without balancing the tree. (Easy)
Start from the root, walk the tree until we find a NIL
pointer, insert the new value there.
Deletion. (Tricky)
Say we want to delete node z
, This operation has three basic cases:
z
has no children: we simply delete thez
by replacing it withNIL
.z
only has one child(either left or right): we replacez
with the only child.z
has both left child and right child: then we findz
’s successory
— which must be inz
’s right subtree — and havey
takez
’s position in the tree. The rest ofz
’s original right subtree becomesy
’s new right subtree, andz
’s left subtree becomesy
’s new left subtree. This case is tricky because it matters whethery
isz
’s right child.- If
y
isz
’s right child, then we replacez
byy
, leavingy
’s right child alone. - Otherwise,
y
lies withinz
’s right subtree but is notz
’s right child (part (d)). In this case, we first replacey
by its own right child, and then we replacez
by y.
- If