题目
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
解题思路
递归和非递归两种方法
代码
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack, res = [root], deque([])
while stack:
cur = stack.pop()
if cur:
res.appendleft(cur.val)
stack.append(cur.left)
stack.append(cur.right)
return res