二叉树的迭代遍历.md 加入 Python 版本的后序遍历新解法

This commit is contained in:
Lane Zhang
2024-10-23 10:22:58 +08:00
parent 42d84f8a7f
commit a36358e068

View File

@ -303,6 +303,44 @@ class Solution:
return result[::-1]
```
#### Python 后序遍历的迭代新解法:
* 本解法不同于前文介绍的`逆转前序遍历调整后的结果`,而是采用了对每个结点直接处理。
```python
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
values = []
stack = []
popped_nodes = set() # 记录值已经被收割了的 nodes
current = root
while current or stack:
if current: # 一次处理完一个结点和他的左右儿子结点,不处理孙子结点,孙子结点由左右儿子等会分别处理。
stack.append(current) # 入栈自己
if current.right:
stack.append(current.right) # 入栈右儿子
if current.left: # 因为栈是后进先出,后序是‘左右中’,所以后加左儿子
stack.append(current.left) # 入栈左儿子
current = None # 会导致后面A处出栈
continue
node = stack.pop() # A处出的是左儿子如果无左儿子出的就是右儿子如果连右儿子也没有出的就是自己了。
# 如果 node 是叶子结点,就可以收割了;如果左右儿子都已经被收割了,也可以收割
if (node.left is None or node.left in popped_nodes) and \
(node.right is None or node.right in popped_nodes):
popped_nodes.add(node)
values.append(node.val)
continue
current = node # 不符合收割条件,说明 node 下还有未入栈的儿子,就去入栈
return values
```
### Go
> 迭代法前序遍历