Skip to Content

Binary Tree Postorder Traversal

Home | Coding Interviews | Simple Data Structures | Binary Tree Postorder Traversal

Given the root of a binary tree, return the postorder traversal of its nodes' values.

# recursive
def postorderTraversal1(self, root):
    res = []
    self.dfs(root, res)
    return res
    
def dfs(self, root, res):
    if root:
        self.dfs(root.left, res)
        self.dfs(root.right, res)
        res.append(root.val)

# iterative        
def postorderTraversal(self, root):
    res, stack = [], [root]
    while stack:
        node = stack.pop()
        if node:
            res.append(node.val)
            stack.append(node.left)
            stack.append(node.right)
    return res[::-1]

Posted by Jamie Meyer 15 days ago