Leetcode 145. Binary Tree Postorder Traversal(非递归后序遍历二叉树)
原题连接
分析
这题的关键在于如何非递归的后序遍历二叉树
焦点在于 左右中 = reverse(中右左)
对比分析
- 先看看先序遍历
- 顺序是中 左 右
- 在递归算法里的顺序如下
- print(root.val)
- visit(root.left)
- visit(root.right)
- 那么它的非递归程序该怎么写
- print(root.val)
- stack.push(root.right)
- stack.push(root.left)
- 注意进栈顺序,先进后出。
- 现在再来看看后序遍历
- 顺序是左 右 中
- 它是中 右 左的逆序
- 中 右 左 就和先序遍历很像了
- 在递归算法里的顺序如下
- print(root.val)
- visit(root.right)
- visit(root.left)
- 那么它的非递归程序该怎么写
- print(root.val)
- stack.push(root.left)
- stack.push(root.right)
- 注意进栈顺序,先进后出。
- 这样一来,后序遍历,转换成了一种先序遍历
CODE
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
ans = collections.deque()
s = [] # stack
s.append(root)
while s:
node = s.pop()
ans.appendleft(node.val)
if node.left:
s.append(node.left)
if node.right:
s.append(node.right)
return list(ans)
欢迎一起来参与leetcode刷题项目
刷题的GitHub: link.