Problem solving & practice
Section 1 of 3
Visit all nodes in specific order using DFS or BFS
Insert, search, delete maintaining BST property
Calculate maximum depth from root to leaf
Find deepest node that is ancestor of both given nodes
Tree problems follow predictable patterns based on traversal methods and recursive thinking. Master these core patterns and most tree interview questions become straightforward applications.
Process node and recursively visit children in specific order
function dfs(node) { if(!node) return; process(node); dfs(node.left); dfs(node.right); }Use queue to process nodes level by level from top to bottom
queue = [root]; while(queue.length) { node = queue.shift(); process(node); if(node.left) queue.push(node.left); if(node.right) queue.push(node.right); }Solve problem by combining solutions from left and right subtrees
function solve(node) { if(!node) return baseCase; left = solve(node.left); right = solve(node.right); return combine(left, right, node); }Maintain current path during traversal to check conditions
function findPath(node, path) { if(!node) return; path.push(node.val); if(isLeaf(node)) checkCondition(path); findPath(node.left, path); findPath(node.right, path); path.pop(); }Build tree from traversal arrays or serialized format
function buildTree(inorder, preorder) { if(!preorder.length) return null; root = new Node(preorder[0]); idx = inorder.indexOf(root.val); root.left = buildTree(inorder.slice(0,idx), preorder.slice(1,idx+1)); root.right = buildTree(inorder.slice(idx+1), preorder.slice(idx+1)); return root; }Compare two trees node by node with synchronized traversal
function isSame(p, q) { if(!p && !q) return true; if(!p || !q) return false; return p.val === q.val && isSame(p.left, q.left) && isSame(p.right, q.right); }Find height of binary tree recursively
Compare two trees for structural equality
Swap left and right children recursively
Check if root-to-leaf path equals target
BFS traversal returning levels as arrays
Ensure in-order traversal is sorted
Find path with maximum sum between any nodes
Convert tree to string and back