Given the root
of a binary tree, return the postorder traversal of its nodes’ values.
In postorder traversal, the nodes are recursively visited as follows:
The binary tree nodes use classes, typically defined as:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
We can solve this problem using two main approaches:
Here are both approaches in Python:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorderTraversal(root: TreeNode):
def helper(node, result):
if node:
helper(node.left, result)
helper(node.right, result)
result.append(node.val)
result = []
helper(root, result)
return result
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorderTraversal(root: TreeNode):
if not root:
return []
stack, output = [root], []
while stack:
node = stack.pop()
output.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return output[::-1]
Both approaches have the same time complexity:
Choose an approach based on the preference for recursion or iteration and constraints such as recursion depth.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?