Understanding Tree Recursion — Level 2
Implementation details, traversal orders, common patterns, and code examples in Python, Java, and C++.
Implementation details, traversal orders, common patterns, and code examples in Python, Java, and C++.
Author
Mr. Oz
Date
Read
8 mins
Level 2
Now that you understand the concept of tree recursion, let's dive into the implementation details. We'll explore different traversal orders, code patterns, and best practices for writing tree recursion in real code.
Before we write recursive functions, let's understand what we're working with:
# Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Each node contains:
The order in which we process nodes matters. There are three main patterns:
Process → Left → Right
Root before children
Left → Process → Right
Root in the middle
Left → Right → Process
Root after children
Key insight: The only difference is WHERE you process the current node relative to the recursive calls!
Most tree recursion problems fall into these categories:
def inorder_traversal(root, result=None):
if result is None:
result = []
if root:
inorder_traversal(root.left, result)
result.append(root.val) # Process
inorder_traversal(root.right, result)
return result
def max_depth(root):
if not root:
return 0
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
return 1 + max(left_depth, right_depth)
def invert_tree(root):
if not root:
return None
root.left, root.right = root.right, root.left
invert_tree(root.left)
invert_tree(root.right)
return root
def invertTree(root):
if not root:
return None
root.left, root.right = root.right, root.left
invertTree(root.left)
invertTree(root.right)
return root
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
Ready for advanced concepts?
Level 1
Learn the fundamentals of tree recursion through an engaging family tree analogy.
Author
Mr. Oz
Duration
5 mins
Level 2
Implementation details, traversal orders, common patterns, and code examples.
Author
Mr. Oz
Duration
8 mins
Level 3
Call stack internals, tail recursion optimization, and memory considerations.
Author
Mr. Oz
Duration
12 mins