Pattern 10 of 22

Tree Traversal Pattern: Template + 225 LeetCode Problems

Choose the order — preorder, inorder, postorder, level — and the problem solves itself.

Easy
41
Medium
142
Hard
42
Time
O(n)

What the tree traversal pattern is

Almost every binary tree problem is a traversal with a small amount of work attached, so the real decision is when the node gets processed relative to its children. Preorder handles a node before descending and is what you want for copying, serialising, or passing information down from the root. Postorder handles it after both children return and is what you want whenever the answer at a node is computed from its subtrees — heights, diameters, subtree sums, the maximum path sum. Inorder is the special one: on a binary search tree it emits the values in sorted order, which turns validation, the kth smallest, and finding the minimum gap into a single scan with a pointer to the previously visited value. Level order is breadth-first search on a tree, done by draining the queue one full level at a time so each level can be handled as a unit. The iterative inorder is the traversal worth being able to write from memory, because it is the one an interviewer will ask for when recursion is ruled out.

When to use it

  • A value at each node depends on its subtrees — that is postorder.
  • The tree is a BST and the question is about sorted order, a kth element, or a range.
  • The answer is per level, or is the shallowest node satisfying a condition.
  • You are asked to serialise, clone, or rebuild a tree from traversal output.

The tree traversal template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 225 problems listed below.

PythonTree Traversal template
def inorder(root):
    result, stack, node = [], [], root

    while node or stack:
        while node:                  # descend as far left as possible
            stack.append(node)
            node = node.left

        node = stack.pop()
        result.append(node.val)      # left subtree finished, so visit now
        node = node.right            # then do the same for the right subtree

    return result

Complexity characteristics

Time
O(n)
Auxiliary space
O(h)where h is the height of the tree

Every node is visited exactly once whatever the order, so the time is linear in the node count. The space is the recursion stack or the explicit stack, which is the height of the tree: O(log n) on a balanced tree and O(n) on a degenerate one, and the degenerate one is what a test harness will hand you. Level-order traversal swaps the stack for a queue holding the widest level, which is up to n/2 nodes on a full tree.

Eyes only

Meet the tree traversal problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 225 tree traversal LeetCode problems

Every problem in the library the tree traversal pattern applies to, grouped by LeetCode's own difficulty rating. 167 of the 225 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Easy (41)

Easy problems
No.Problem
0094Binary Tree Inorder Traversal
0100Same Tree
0101Symmetric Tree
0104Maximum Depth of Binary Tree
0108Convert Sorted Array to Binary Search Tree
0110Balanced Binary Tree
0111Minimum Depth of Binary Tree
0112Path Sum
0144Binary Tree Preorder Traversal
0145Binary Tree Postorder Traversal
0222Count Complete Tree Nodes
0226Invert Binary Tree
0257Binary Tree Paths
0404Sum of Left Leaves
0501Find Mode in Binary Search Tree
0530Minimum Absolute Difference in BST
0543Diameter of Binary Tree
0559Maximum Depth of N-ary Tree
0563Binary Tree Tilt
0572Subtree of Another Tree
0589N-ary Tree Preorder Traversal
0590N-ary Tree Postorder Traversal
0617Merge Two Binary Trees
0637Average of Levels in Binary Tree
0653Two Sum IV - Input is a BST
0671Second Minimum Node In a Binary Tree
0700Search in a Binary Search Tree
0703Kth Largest Element in a Stream
0872Leaf-Similar Trees
0270Closest Binary Search Tree ValuePremium
0783Minimum Distance Between BST Nodes
0897Increasing Order Search Tree
0938Range Sum of BST
0965Univalued Binary Tree
0993Cousins in Binary Tree
1022Sum of Root To Leaf Binary Numbers
1379Find a Corresponding Node of a Binary Tree in a Clone of That Tree
1469Find All The Lonely NodesPremium
2236Root Equals Sum of Children
2331Evaluate Boolean Binary Tree
2689Extract Kth Character From The Rope TreePremium

Medium (142)

Medium problems
No.Problem
0095Unique Binary Search Trees II
0096Unique Binary Search Trees
0098Validate Binary Search Tree
0099Recover Binary Search Tree
0102Binary Tree Level Order Traversal
0103Binary Tree Zigzag Level Order Traversal
0105Construct Binary Tree from Preorder and Inorder Traversal
0106Construct Binary Tree from Inorder and Postorder Traversal
0107Binary Tree Level Order Traversal II
0109Convert Sorted List to Binary Search Tree
0113Path Sum II
0114Flatten Binary Tree to Linked List
0116Populating Next Right Pointers in Each Node
0117Populating Next Right Pointers in Each Node II
0129Sum Root to Leaf Numbers
0173Binary Search Tree Iterator
0199Binary Tree Right Side View
0230Kth Smallest Element in a BST
0235Lowest Common Ancestor of a Binary Search Tree
0236Lowest Common Ancestor of a Binary Tree
0331Verify Preorder Serialization of a Binary Tree
0337House Robber III
0341Flatten Nested List Iterator
0427Construct Quad Tree
0429N-ary Tree Level Order Traversal
0437Path Sum III
0449Serialize and Deserialize BST
0450Delete Node in a BST
0508Most Frequent Subtree Sum
0513Find Bottom Left Tree Value
0515Find Largest Value in Each Tree Row
0538Convert BST to Greater Tree
0558Logical OR of Two Binary Grids Represented as Quad-Trees
0606Construct String from Binary Tree
0623Add One Row to Tree
0652Find Duplicate Subtrees
0654Maximum Binary Tree
0655Print Binary Tree
0662Maximum Width of Binary Tree
0669Trim a Binary Search Tree
0687Longest Univalue Path
0690Employee Importance
0701Insert into a Binary Search Tree
1161Maximum Level Sum of a Binary Tree
1372Longest ZigZag Path in a Binary Tree
1448Count Good Nodes in Binary Tree
0156Binary Tree Upside DownPremium
0250Count Univalue SubtreesPremium
0255Verify Preorder Sequence in Binary Search TreePremium
0285Inorder Successor in BSTPremium
0298Binary Tree Longest Consecutive SequencePremium
0314Binary Tree Vertical Order TraversalPremium
0333Largest BST SubtreePremium
0366Find Leaves of Binary TreePremium
0426Convert Binary Search Tree to Sorted Doubly Linked ListPremium
0510Inorder Successor in BST IIPremium
0536Construct Binary Tree from StringPremium
0545Boundary of Binary TreePremium
0549Binary Tree Longest Consecutive Sequence IIPremium
0582Kill ProcessPremium
0663Equal Tree PartitionPremium
0666Path Sum IVPremium
0742Closest Leaf in a Binary TreePremium
0776Split BSTPremium
0814Binary Tree Pruning
0863All Nodes Distance K in Binary Tree
0865Smallest Subtree with all the Deepest Nodes
0889Construct Binary Tree from Preorder and Postorder Traversal
0894All Possible Full Binary Trees
0919Complete Binary Tree Inserter
0951Flip Equivalent Binary Trees
0958Check Completeness of a Binary Tree
0971Flip Binary Tree To Match Preorder Traversal
0979Distribute Coins in Binary Tree
0988Smallest String Starting From Leaf
0998Maximum Binary Tree II
1008Construct Binary Search Tree from Preorder Traversal
1026Maximum Difference Between Node and Ancestor
1038Binary Search Tree to Greater Sum Tree
1080Insufficient Nodes in Root to Leaf Paths
1104Path In Zigzag Labelled Binary Tree
1110Delete Nodes And Return Forest
1120Maximum Average SubtreePremium
1123Lowest Common Ancestor of Deepest Leaves
1145Binary Tree Coloring Game
1214Two Sum BSTsPremium
1245Tree DiameterPremium
1257Smallest Common RegionPremium
1261Find Elements in a Contaminated Binary Tree
1273Delete Tree NodesPremium
1302Deepest Leaves Sum
1305All Elements in Two Binary Search Trees
1315Sum of Nodes with Even-Valued Grandparent
1325Delete Leaves With a Given Value
1339Maximum Product of Splitted Binary Tree
1361Validate Binary Tree Nodes
1367Linked List in Binary Tree
1376Time Needed to Inform All Employees
1382Balance a Binary Search Tree
1430Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary TreePremium
1443Minimum Time to Collect All Apples in a Tree
1457Pseudo-Palindromic Paths in a Binary Tree
1485Clone Binary Tree With Random PointerPremium
1490Clone N-ary TreePremium
1506Find Root of N-Ary TreePremium
1519Number of Nodes in the Sub-Tree With the Same Label
1522Diameter of N-Ary TreePremium
1530Number of Good Leaf Nodes Pairs
1586Binary Search Tree Iterator IIPremium
1600Throne Inheritance
1602Find Nearest Right Node in Binary TreePremium
1609Even Odd Tree
1612Check If Two Expression Trees are EquivalentPremium
1628Design an Expression Tree With Evaluate FunctionPremium
1644Lowest Common Ancestor of a Binary Tree IIPremium
1650Lowest Common Ancestor of a Binary Tree IIIPremium
1660Correct a Binary TreePremium
1666Change the Root of a Binary TreePremium
1676Lowest Common Ancestor of a Binary Tree IVPremium
1740Find Distance in a Binary TreePremium
1902Depth of BST Given Insertion OrderPremium
1973Count Nodes Equal to Sum of DescendantsPremium
1993Operations on Tree
2049Count Nodes With the Highest Score
2096Step-By-Step Directions From a Binary Tree Node to Another
2196Create Binary Tree From Descriptions
2265Count Nodes Equal to Average of Subtree
2368Reachable Nodes With Restrictions
2378Choose Edges to Maximize Score in a TreePremium
2385Amount of Time for Binary Tree to Be Infected
2415Reverse Odd Levels of Binary Tree
2445Number of Nodes With Value OnePremium
2467Most Profitable Path in a Tree
2471Minimum Number of Operations to Sort a Binary Tree by Level
2476Closest Nodes Queries in a Binary Search Tree
2477Minimum Fuel Cost to Report to the Capital
2583Kth Largest Sum in a Binary Tree
2641Cousins in Binary Tree II
2673Make Costs of Paths Equal in a Binary Tree
2764Is Array a Preorder of Some ‌Binary TreePremium
2773Height of Special Binary TreePremium
2925Maximum Score After Applying Operations on a Tree

Hard (42)

Hard problems
No.Problem
0124Binary Tree Maximum Path Sum
0297Serialize and Deserialize Binary Tree
0272Closest Binary Search Tree Value IIPremium
0428Serialize and Deserialize N-ary TreePremium
0431Encode N-ary Tree to Binary TreePremium
0834Sum of Distances in Tree
0968Binary Tree Cameras
0987Vertical Order Traversal of a Binary Tree
1028Recover a Tree From Preorder Traversal
1373Maximum Sum BST in Binary Tree
1377Frog Position After T Seconds
1483Kth Ancestor of a Tree Node
1516Move Sub-Tree of N-Ary TreePremium
1569Number of Ways to Reorder Array to Get Same BST
1597Build Binary Expression Tree From Infix ExpressionPremium
1617Count Subtrees With Max Distance Between Cities
1719Number Of Ways To Reconstruct A Tree
1766Tree of Coprimes
1916Count Ways to Build Rooms in an Ant Colony
1932Merge BSTs to Create Single BST
2003Smallest Missing Genetic Value in Each Subtree
2005Subtree Removal Game with Fibonacci TreePremium
2246Longest Path With Different Adjacent Characters
2277Closest Node to Path in TreePremium
2313Minimum Flips in Binary Tree to Get ResultPremium
2322Minimum Score After Removals on a Tree
2421Number of Good Paths
2440Create Components With Same Value
2458Height of Binary Tree After Subtree Removal Queries
2479Maximum XOR of Two Non-Overlapping SubtreesPremium
2509Cycle Length Queries in a Tree
2538Difference Between Maximum and Minimum Price Sum
2581Count Number of Possible Root Nodes
2603Collect Coins in a Tree
2646Minimize the Total Price of the Trips
2791Count Paths That Can Form a Palindrome in a Tree
2792Count Nodes That Are Great EnoughPremium
2846Minimum Edge Weight Equilibrium Queries in a Tree
2867Count Valid Paths in a Tree
2872Maximum Number of K-Divisible Components
2920Maximum Points After Collecting Coins From All Nodes
2973Find Number of Coins to Place in Tree Nodes

Tree Traversal pattern FAQ

What is the tree traversal pattern?

Almost every binary tree problem is a traversal with a small amount of work attached, so the real decision is when the node gets processed relative to its children.

How many LeetCode problems use the tree traversal pattern?

This page lists 225 LeetCode problems that the tree traversal pattern applies to: 41 Easy, 142 Medium and 42 Hard. 167 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the tree traversal pattern?

O(n) time and O(h), where h is the height of the tree space. Every node is visited exactly once whatever the order, so the time is linear in the node count. The space is the recursion stack or the explicit stack, which is the height of the tree: O(log n) on a balanced tree and O(n) on a degenerate one, and the degenerate one is what a test harness will hand you. Level-order traversal swaps the stack for a queue holding the widest level, which is up to n/2 nodes on a full tree.

When should I use the tree traversal pattern in an interview?

A value at each node depends on its subtrees — that is postorder. The tree is a BST and the question is about sorted order, a kth element, or a range.

Which tree traversal problem should I start with?

LeetCode 94. Binary Tree Inorder Traversal is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to tree traversal?

Depth-First Search, Breadth-First Search, Backtracking, Trie. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.