Trees — Complete Guide: All Patterns & Problem Index

Sanjeev SharmaSanjeev Sharma
6 min read

Advertisement

Trees — Complete Pattern Guide

Problems 346–420 · 75 posts · Easy × 15, Medium × 40, Hard × 20


Core Patterns

#PatternKey IdeaExample
1Inorder / Preorder / PostorderRecursive DFSTree traversals, BST validation
2Level Order BFSQueue layer by layerLevel order, zigzag, right view
3Path SumDFS with running sumPath Sum I/II/III, Max Path Sum
4BST PropertyLeft < root < rightValidate BST, Search BST, Insert/Delete
5LCA (Lowest Common Ancestor)Find split pointLCA of BST/BT, Distance
6Tree ConstructionFrom traversalsBuild from Preorder+Inorder
7Serialize/DeserializeBFS or DFS encodingSerialize BT, Codec
8Tree DPdp on subtreesDiameter, Max Path, House Robber III
9Morris TraversalO(1) space inorderInorder without recursion/stack

Templates

DFS Traversals

def inorder(root):
    if not root: return []
    return inorder(root.left) + [root.val] + inorder(root.right)

def preorder(root):
    if not root: return []
    return [root.val] + preorder(root.left) + preorder(root.right)

def postorder(root):
    if not root: return []
    return postorder(root.left) + postorder(root.right) + [root.val]

Iterative Inorder

def inorder_iter(root):
    stack, result = [], []
    curr = root
    while curr or stack:
        while curr: stack.append(curr); curr = curr.left
        curr = stack.pop()
        result.append(curr.val)
        curr = curr.right
    return result

BFS Level Order

from collections import deque
def level_order(root):
    if not root: return []
    queue, result = deque([root]), []
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)
        result.append(level)
    return result

Path Sum DFS

def has_path_sum(root, target):
    if not root: return False
    if not root.left and not root.right: return root.val == target
    return has_path_sum(root.left, target-root.val) or            has_path_sum(root.right, target-root.val)

LCA Template

def lca(root, p, q):
    if not root or root == p or root == q: return root
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    return root if left and right else left or right

Tree DP (diameter pattern)

def diameter(root):
    self.ans = 0
    def depth(node):
        if not node: return 0
        L, R = depth(node.left), depth(node.right)
        self.ans = max(self.ans, L+R)
        return max(L, R)+1
    depth(root)
    return self.ans

Problem Index — Trees

Easy (346–360)

#Problem
346Maximum Depth of Binary Tree
347Minimum Depth of Binary Tree
348Invert Binary Tree
349Symmetric Tree
350Path Sum I
351Same Tree
352Count Complete Tree Nodes
353Balanced Binary Tree
354Merge Two Binary Trees
355Sum of Left Leaves
356Find Mode in BST
357Range Sum of BST
358Search in BST
359Insert into BST
360Convert Sorted Array to BST

Medium (361–395)

#Problem
361Binary Tree Level Order Traversal
362Binary Tree Zigzag Level Order
363Binary Tree Right Side View
364Average of Levels
365Path Sum II
366Path Sum III
367Diameter of Binary Tree
368Flatten Binary Tree to LL
369Construct from Preorder + Inorder
370Construct from Inorder + Postorder
371Validate BST
372Kth Smallest in BST
373Delete Node in BST
374LCA of Binary Tree
375LCA of BST
376Binary Tree Level Order II (bottom-up)
377Populating Next Right Pointers
378Binary Tree Maximum Path Sum (prep)
379All Nodes Distance K in Binary Tree
380Sum Root to Leaf Numbers
381Maximum Width of Binary Tree
382Find Leaves of Binary Tree
383Step-By-Step Directions
384Check Completeness of Binary Tree
385Count Good Nodes
386Convert BST to Greater Tree
387Recover BST (swap 2 nodes)
388House Robber III
389Find Duplicate Subtrees
390Serialize and Deserialize BST
391Unique BSTs (Catalan Number)
392Unique BSTs II
393Trim a BST
394Lowest Common Ancestor (all variations)
395Vertical Order Traversal

Hard (396–420)

#Problem
396Binary Tree Maximum Path Sum
397Serialize and Deserialize Binary Tree
398Recover Binary Search Tree
399Binary Tree Cameras
400Count of Smaller Numbers (BST)
401Vertical Order Traversal (hard)
402Distribute Coins in Binary Tree
403Maximum Sum BST in Binary Tree
404Number of Ways to Reorder Array to Same BST
405Closest Leaf in a Binary Tree
406Flip Binary Tree to Match Preorder
407Build BST from Preorder Traversal
408Largest BST Subtree
409Kth Ancestor of a Tree Node
410Step-By-Step Directions Hard
411Maximum Depth of N-ary Tree
412Serialize and Deserialize N-ary Tree
413LCA with Parent Pointers
414Find Root of N-ary Tree
415Trees Master Recap

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro