Trees & BST · Pattern 1 of 12
Tree recursion: traversals, depth and comparing trees
Handle null, recurse on the left and right subtrees, and combine their answers at the node. Preorder, inorder and postorder only differ in when you visit the node.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Visit every node in preorder, inorder or postorder
- A value that is built from the two subtrees (depth, size, mirror)
- Compare two trees, or a tree with itself mirrored
- Do the same traversal without recursion, using a stack
The template
int maxDepth(TreeNode root) {
if (root == null) return 0; // empty tree: depth 0
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return p == q; // true only if both are empty
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
// recursive preorder: move out.add(...) between or after the calls for inorder / postorder
void preorder(TreeNode node, List<Integer> out) {
if (node == null) return;
out.add(node.val);
preorder(node.left, out);
preorder(node.right, out);
}
// iterative inorder: your own stack replaces the call stack
List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode cur = root;
while (cur != null || !st.isEmpty()) {
while (cur != null) { st.push(cur); cur = cur.left; } // go left as far as possible
cur = st.pop();
res.add(cur.val); // visit
cur = cur.right; // then the right subtree
}
return res;
} def max_depth(root):
if not root:
return 0 # empty tree: depth 0
return 1 + max(max_depth(root.left), max_depth(root.right))
def is_same_tree(p, q):
if not p or not q:
return p is q # true only if both are empty
return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
# recursive preorder: move out.append(...) between or after the calls for inorder / postorder
def preorder(node, out):
if not node:
return
out.append(node.val)
preorder(node.left, out)
preorder(node.right, out)
# iterative inorder: your own stack replaces the call stack
def inorder_traversal(root):
res, st, cur = [], [], root
while cur or st:
while cur: # go left as far as possible
st.append(cur)
cur = cur.left
cur = st.pop()
res.append(cur.val) # visit
cur = cur.right # then the right subtree
return res int maxDepth(TreeNode* root) {
if (!root) return 0; // empty tree: depth 0
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p || !q) return p == q; // true only if both are empty
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
// recursive preorder: move out.push_back(...) between or after the calls for inorder / postorder
void preorder(TreeNode* node, vector<int>& out) {
if (!node) return;
out.push_back(node->val);
preorder(node->left, out);
preorder(node->right, out);
}
// iterative inorder: your own stack replaces the call stack
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty()) {
while (cur) { st.push(cur); cur = cur->left; } // go left as far as possible
cur = st.top(); st.pop();
res.push_back(cur->val); // visit
cur = cur->right; // then the right subtree
}
return res;
} function maxDepth(root) {
if (!root) return 0; // empty tree: depth 0
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
function isSameTree(p, q) {
if (!p || !q) return p === q; // true only if both are empty
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
// recursive preorder: move out.push(...) between or after the calls for inorder / postorder
function preorder(node, out) {
if (!node) return;
out.push(node.val);
preorder(node.left, out);
preorder(node.right, out);
}
// iterative inorder: your own stack replaces the call stack
function inorderTraversal(root) {
const res = [], st = [];
let cur = root;
while (cur || st.length) {
while (cur) { st.push(cur); cur = cur.left; } // go left as far as possible
cur = st.pop();
res.push(cur.val); // visit
cur = cur.right; // then the right subtree
}
return res;
} The variations
-
1Recursive traversals
The same three lines in a different order: visit the node before the children (preorder), between them (inorder) or after them (postorder).
-
2Iterative traversals with a stack
Push what the call stack would remember. Inorder goes left as far as it can, pops and turns right. Preorder pops a node and pushes the right child before the left one.
-
3Combine the two subtree answers
Ask both children for their answer, then build yours: depth is
1 + max, a mirror swaps the children. The second minimum and the upside-down tree are the same idea with a different combine step.Now you solve -
4Walk two trees together
Recurse on a pair of nodes. Both null is a match, one null is a mismatch, otherwise compare values and recurse on the matching pairs of children.
Now you solve -
5Carry a value down the path
Pass what the path has built so far as a parameter (
number * 10 + val) and add it to the answer at each leaf. -
6More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Checking
root.left.valbefore checking thatroot.leftexists. - Symmetric tree: comparing
left.leftwithright.left. A mirror pairs the outside children (left.left,right.right) and the inside ones. - Iterative postorder: the simple trick (preorder as node, right, left, then reverse) is fine, but say so; it uses O(n) extra space.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.