DSA · Intermediate · Pattern 4 of 10
Binary Trees
20 problems.
Your progress0%
- 1st Visit
- 0/20
- 2nd Visit
- 0/20
- Revise
- 0/20
About this pattern
Binary tree problems are recursive by nature: every node has a left and a right subtree, and most answers combine results from the two subtrees with the value at the node. Depth-first traversal (preorder, inorder, postorder) suits questions about heights, paths and subtree properties; breadth-first traversal with a queue processes the tree level by level.
Decide first what each recursive call returns and what information must be passed down from ancestors, such as the largest value seen so far. Signals include depth, levels, views from one side, or rebuilding a tree from traversals. Each node is visited once, giving O(n) time and O(h) stack space for height h.
// DFS: information flows down as parameters and up as return values.
int height(TreeNode* node) {
if (!node) return 0;
return 1 + max(height(node->left), height(node->right));
}
// BFS: process the tree one level at a time.
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
int sz = q.size(); // nodes on the current level
for (int i = 0; i < sz; ++i) {
TreeNode* cur = q.front(); q.pop();
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}