#145 Binary Tree Postorder Traversal
Given the
root
of a binary tree, return the postorder traversal of its nodes' values.
Iterative的解题思路:
1.点存在就先存进stack。存好之后,看点的左叶是否存在。是的话重复1,并指针cur左下移;不是的话走2.
2.看点的右叶是否存在,存在的话重复1,并指针cur右下移;不是的话走3.
3.一旦这个点的左叶右叶都不存在或已经处理过了,就从stack中pop out,并append这个点的值给out。
4.如果此时stack里还有值的话,cur指针指向stack的最后一个值.
5.判断cur这个点与上一个输出的点是否为右叶关系。是的话重复3,不是的话重复2。如果stack已经空了,就输出out。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out = []
stack = [root]
# step 1
while root:
while root.left:
stack.append(root.left) # store all the left leaves
root = root.left
# when running out of left nodes, check if right node exists.
while True:
# step 2
if root.right:
stack.append(root.right)
root = root.right
break # back to step 1
# step 3
else:
while True:
end = stack.pop()
out.append(end.val) # time to pop out
# step 4
if stack:
root = stack[-1]
# step 5
if end == root.right:
continue # back to step 3
else:
break # back to step 2
else:
return out
runtime:
recursive的解题思路:
1.先判断是否为空
2.先处理左叶,再处理右叶,最后append中间点的值
3.append的永远都是最外面统一的out list。(所以要新建个函数,不然会list of list的情况)
4.输出out。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def dfs(node):
if not node: return
dfs(node.left)
dfs(node.right)
res.append(node.val)
res = []
dfs(root)
return res
runtime:
这个preorder, inorder, postorder系列,用两种不同的思路确实太难了。还是要多复习才行。