#145. Binary Tree Postorder Traversal | LeetCode Python Solution
Problem
LeetCode Problem
- Binary Tree Postorder Traversal
Python Solution with Recursion
# 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:
# Postorder (Left, Right, Root)
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# Handle base cases
if root is None:
return []
elif root.left is None and root.right is None:
return [root.val]
# Output list
output = []
# Collect left subtree values
if root.left is not None:
output = self.postorderTraversal(root.left)
# Collect right subtree values
if root.right is not None:
output.extend(self.postorderTraversal(root.right))
# Collect root node value
output.append(root.val)
return output