Binary Trees 101
Intermediate · 4 chapters · 8 min read · Think recursively: solve the tree by trusting the answer from each subtree.
Practise this in the app All guides
Trees and the recursive mindset
What a binary tree is
A binary tree is a set of nodes where each node has a value and up to two children, left and right. The top node is the root; nodes without children are leaves. The height is the number of edges (or nodes, depending on the definition — clarify) on the longest root-to-leaf path. A balanced tree with n nodes has height about log n; a skewed one can have height n.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
A binary search tree (BST) adds an ordering rule: every value in the left subtree is smaller than the node, every value in the right subtree is larger. An in-order traversal of a BST visits values in sorted order, which solves many BST questions directly.
Signals in a problem statement
- The input is a
TreeNoderoot. - "Depth", "height", "diameter", "path sum", "balanced", "symmetric", "mirror".
- "Level by level", "right side view", "zigzag" — breadth-first search with a queue.
- "Valid BST", "k-th smallest in a BST", "lowest common ancestor".
- "Build the tree from preorder and inorder" or "serialise and deserialise".
The recursive mindset
Most tree solutions follow one shape: ask each child for its answer, combine with the current node, return. You do not trace the whole recursion in your head. You trust that depth(node.left) returns the correct depth, and only reason about one node. The base case is almost always if node is None. If you can say "a node's answer is f(left answer, right answer, node value)", the code is three lines.
Core patterns with templates
1. Bottom-up: combine children's answers
def max_depth(node):
if not node:
return 0
return 1 + max(max_depth(node.left), max_depth(node.right))
def invert(node):
if node:
node.left, node.right = invert(node.right), invert(node.left)
return node
2. Compare two subtrees together
def is_symmetric(root):
def mirror(a, b):
if not a or not b:
return a is b
return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)
return mirror(root, root)
3. Top-down: pass constraints downward
def is_valid_bst(node, lo=float("-inf"), hi=float("inf")):
if not node:
return True
if not lo < node.val < hi:
return False
return is_valid_bst(node.left, lo, node.val) and is_valid_bst(node.right, node.val, hi)
Checking only a node against its direct children is the classic wrong answer; the bounds carry the whole ancestry.
4. Level-order traversal (BFS)
from collections import deque
def level_order(root):
if not root:
return []
out, q = [], deque([root])
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
out.append(level)
return out
5. Return one thing, track another
For the maximum path sum, each call returns the best downward path from the node, while a shared variable records the best path that bends through the node.
def max_path_sum(root):
best = float("-inf")
def down(node):
nonlocal best
if not node:
return 0
l = max(down(node.left), 0)
r = max(down(node.right), 0)
best = max(best, node.val + l + r)
return node.val + max(l, r)
down(root)
return bestComplexity, mistakes and edge cases
Complexity
| Task | Time | Space |
|---|---|---|
| Any full traversal (DFS or BFS) | O(n) | O(h) recursion or O(w) queue |
| BST search / insert | O(h) | O(1) iterative |
| k-th smallest via in-order | O(h + k) | O(h) |
| Build from preorder + inorder (with index map) | O(n) | O(n) |
Here h is the height and w the maximum width. For a balanced tree h ≈ log n; for a skewed tree h = n, so recursion depth can reach 10⁵ and break Python's default limit. Mention sys.setrecursionlimit or an explicit stack if the constraints are large.
Common mistakes
- Validating a BST locally (only parent versus child) instead of with bounds or an in-order check.
- Duplicates in a BST. Ask whether equal values are allowed and on which side.
- Negative values in path problems. Clamp a child's contribution at 0, and initialise the best answer to negative infinity, not 0, so an all-negative tree works.
- Confusing what the function returns with what it records. In diameter and path-sum problems, the returned value is a one-sided path; the global answer is two-sided.
- Searching for the root in inorder with
list.indexon every call, turning an O(n) construction into O(n²). Build a value-to-index map first. - Forgetting the
Noneroot case at the top level.
Edge cases
Empty tree, single node, only left children (a linked list in disguise), complete tree, all equal values, negative values, very deep trees.
Iterative in-order traversal
def kth_smallest(root, k):
st, node = [], root
while st or node:
while node:
st.append(node)
node = node.left
node = st.pop()
k -= 1
if k == 0:
return node.val
node = node.right
Being able to write this without recursion is a common follow-up.
Variations and practise
How interviewers twist it
- Views of a tree. Right side view: the last node of each BFS level. Left view: the first. Zigzag: reverse every other level.
- Lowest common ancestor. In a BST, walk down until the two values split. In a general tree, return the node if either side found a target and both sides report a hit.
- Diameter. Same shape as maximum path sum, but counting edges instead of adding values.
- Construct from traversals. The first preorder value is the root; its position in inorder splits the left and right subtrees. Keep a pointer into preorder and a map for inorder positions.
- Serialise and deserialise. Preorder with a marker for
None(for example#) is enough to rebuild the tree uniquely. - Path sums to a target. Combine a DFS with a prefix-sum counter of sums along the current root-to-node path, removing the current sum when you backtrack.
- Balanced check in one pass. Return the height, or -1 as soon as any subtree is unbalanced.
How to explain it
State the recursive contract: "down(node) returns the best path that starts at node and goes down; I update the global best with the path that bends at node." With that sentence, the interviewer can follow every line you write.
Practise
The problems below move from depth, inversion and symmetry, through level-order traversal and BST validation, to the k-th smallest element, building a tree from two traversals, and the maximum path sum. Write the recursive contract as a comment before each solution.
Practise
Easy
- 1756. Maximum Depth of Binary Tree
- 1757. Invert Binary Tree
- 1758. Symmetric Tree
- 1765. Count Every Node in the Orchard
- 1770. Mirror Image Pair
- 1771. Count the Bare Twigs
- 1772. Shallowest Leaf Depth
- 1773. Largest Value Anywhere in the Tree
- 1774. Total of Leaves Hanging on the Left
- 1775. Are Two Trees Exact Copies
- 1776. Is the Value Somewhere in the Tree
- 1777. Find a Key in a Sorted Tree
- 1778. Place a New Key in a BST
- 1779. Smallest Gap Between Two Tags
- 1780. Total of Tags Inside a Window
- 1781. Visit Order: Node Before Children
- 1782. Visit Order: Left, Node, Right
- 1783. Visit Order: Children Before Node
- 1784. Is the Tree on an Even Keel
- 1785. Longest Span Between Two Nodes
- 1786. Does Any Branch Hit the Target
- 1787. Spell Out Every Branch
- 1788. Overlay Two Orchards
- 1789. Do All Nodes Carry One Value
- 1790. Build a Balanced Index from Sorted IDs
- 1791. Is One Tree Hidden Inside Another
- 1792. Are the Two Nodes Cousins
- 1793. Total of Each Row
- 1794. Do Two Trees Share a Leaf Row
- 1795. Total Imbalance Score
- 1796. Most Frequent Tags in a BST
- 1797. Two Tags That Add Up
- 1798. Unroll a BST into a Chain
- 1799. Parent Equals Its Children's Total
- 1800. Evaluate a Logic Gate Tree
- 1801. Tag Closest to a Target
- 1802. Nodes with a Grandparent Divisible by Three
- 1803. Depth of a Given Value
- 1804. Height of a Family Tree from Parent Links
- 1805. Find the Founder from Parent-Child Records
- 1806. How Many Nodes Sit on Level k
- 1807. Which Row Has the Most Nodes
- 1808. Odd Rows Minus Even Rows
- 1809. Is Every Level Completely Filled
- 1810. Zero or Two Children Everywhere
- 1811. Does Any Value Repeat
- 1812. Count Parents with a Single Child
- 1813. Snip Zero-Valued Tips Once
- 1814. Floor and Ceiling in a BST
- 1815. Spread Between Smallest and Largest Tag
- 1816. Cheapest Root-to-Leaf Branch
- 1817. List the Only Children
- 1818. Write a Tree in Bracket Notation
- 1819. Depth-Weighted Total
- 1820. Nodes Smaller Than the Root
- 1821. Is One Node an Ancestor of Another
- 1822. Nodes That Copy Their Parent
- 1823. Strictly Rising Branches
- 1824. Swap Children on Even Rows
- 1825. Cut Everything Below Depth k
- 1826. Label Each Node with Its Subtree Size
- 1827. Nodes Whose Value Equals Their Depth
- 1828. Height of a BST Built by Insertions
- 1829. Spread of Each Row
- 1830. Follow the Turns
- 1831. Directions from the Root to a Node
- 1832. Second-Smallest in a Min-Merge Tree
- 1833. Climb k Levels Up
- 1834. Total Weight of a Team
- 1835. Size of Every Team
- 1836. Hub of a Star Network
- 1837. Paint a Tree Without Clashes
- 1838. Nodes Larger Than Everything Below
- 1839. Does the Array Obey the Max-Heap Rule
- 1840. Height of a Many-Child Tree
- 1841. Visit a Many-Child Tree Top-Down
- 1842. Count Words Starting a Certain Way
- 1843. Count the Leaves in a Parent Array
- 1968. List Every Ancestor
- 1971. Pair Sum on One Level
- 1972. Strongest Branch Signature
- 1973. Alternating Sum Across Each Row
- 1974. Median of Each Row
- 2044. Decode Bits with a Code Tree
- 2057. Path to a Label in an Endless Tree
Medium
- 1759. Binary Tree Level Order Traversal
- 1760. Validate Binary Search Tree
- 1761. Kth Smallest Element in a BST
- 1762. Construct Binary Tree from Preorder and Inorder Traversal
- 1766. Read the Rows in Snake Order
- 1767. Rows from the Ground Up
- 1768. What You See from the East Side
- 1844. Peak of Each Row
- 1845. Widest Row Counting Gaps
- 1846. Deepest Leftmost Leaf
- 1847. Weight of the Lowest Row
- 1848. List the Tree Column by Column
- 1849. What a Drone Sees from Above
- 1850. Trace the Outline of a Tree
- 1851. Slice the Tree Diagonally
- 1852. Row with the Largest Total
- 1853. Alternating Parity Rows
- 1854. No Gaps Before the End
- 1855. Replace Each Node with Its Cousins' Total
- 1856. Reverse the Odd Rows of a Perfect Tree
- 1857. Swaps to Sort Every Row
- 1858. Insert a Row of New Nodes
- 1859. Kth Heaviest Row
- 1860. Neighbour to the Right
- 1861. All Branches That Spend the Budget Exactly
- 1862. Downward Runs with a Target Sum
- 1863. Read Each Branch as a Number
- 1864. Nodes Not Overshadowed by Ancestors
- 1865. Largest Gap to an Ancestor
- 1866. Longest Switchback Walk
- 1867. Longest Path with One Label
- 1868. Longest Counting-Up Run
- 1869. Branches That Could Read as Palindromes
- 1870. Smallest Word Read from a Leaf Upward
- 1871. Nodes Equal to Their Subtree's Average
- 1872. Best Single Cut
- 1873. Cut into Two Equal Halves
- 1874. Most Common Subtree Total
- 1875. Spread the Coins Evenly
- 1876. Treasure Haul Without Neighbours
- 1877. Forest Sizes After Removals
- 1878. Nearest Shared Ancestor
- 1879. Root of the Deepest Cluster
- 1880. Nodes Exactly k Steps Away
- 1881. Minutes for Rot to Spread
- 1882. Hops Between Two Nodes
- 1883. Turn-by-Turn Directions in a Tree
- 1884. Flatten into a Preorder Chain
- 1885. Equal up to Child Swaps
- 1886. Swaps to Match a Visit Order
- 1887. Rebuild a Full Tree from Pre- and Post-Order
- 1888. Rebuild a BST from Its Preorder
- 1889. Could This Be a BST Preorder
- 1890. Build the Peak-Rooted Tree
- 1891. How Many BST Shapes for 1..n
- 1892. Fix the Two Swapped Tags
- 1893. Remove a Key from a BST
- 1894. Clip a BST to a Range
- 1895. Add All Larger Tags
- 1896. Next Tag After x
- 1897. k Tags Nearest a Target
- 1898. Step Through a BST
- 1899. A Pair Across Two BSTs
- 1900. All Tags from Two BSTs in Order
- 1901. Rebalance a Lopsided BST
- 1902. Biggest Valid BST Inside a Tree
- 1903. Count a Complete Tree Fast
- 1904. Balanced BST from a Sorted Chain
- 1905. Prune Weak Branches
- 1906. Strip Target Leaves Until None Remain
- 1907. Count Uniform Subtrees
- 1908. Peel the Tree Leaf Layer by Layer
- 1909. Nearest Leaf to a Marked Node
- 1910. Can the Second Painter Win
- 1911. Does the Sequence Trace a Branch
- 1912. Subtree with the Highest Average
- 1913. Nodes Equal to Their Descendants' Total
- 1914. A Chain Hidden Along a Downward Path
- 1915. Turn a Left-Leaning Tree Upside Down
- 1916. Is the Comma String a Valid Preorder
- 1917. Assemble a Tree from Parent-Child Records
- 1918. Rebuild from In-Order and Row Order
- 1919. Parenthesise a Postfix Expression
- 1920. Parse a Bracketed Tree
- 1921. Shared Ancestor in a Sorted Tree
- 1922. Shared Ancestor of a Whole Group
- 1923. Same Tags, Different Shapes
- 1924. Middle Tag of a BST
- 1925. Rows of a Many-Child Tree
- 1926. Time for News to Reach Everyone
- 1927. Shut Down a Process Tree
- 1928. Line of Succession
- 1929. Is This Network a Tree
- 1930. Do These Child Links Form One Binary Tree
- 1931. Same Org Chart Up to Reordering
- 1932. Most Damaging Node to Remove
- 1933. Gather All Marked Nodes and Return
- 1934. Same-Letter Descendants
- 1935. Best Roots for a Short Tree
- 1936. Longest Trail in a Park
- 1937. Party Without Direct Bosses
- 1938. Guard Every Corridor
- 1939. Farthest Distance from Every Node
- 1940. Sum of All Pairwise Hops
- 1941. Nearest Shop for Every House
- 1942. Count Calm Selections
- 1943. Count Connected Clusters
- 1944. Pair Up Neighbours
- 1945. Leaf Pairs Within Reach
- 1946. Equalise Every Root-to-Leaf Cost
- 1947. Cheapest Product Tree over a Row
- 1948. Total Cost of an Optimal Prefix Code
- 1949. Factor Trees from a Set
- 1950. Prefix Dictionary Operations
- 1951. Dictionary with Wildcard Lookups
- 1952. Shorten Words to Their Stems
- 1953. Longest Word Grown Letter by Letter
- 1954. Count Distinct Substrings
- 1955. Count Misplaced Nodes
- 1956. Shortest Suffix-Sharing Encoding
- 1957. Drop Nested Folders
- 1958. Capital-Letter Pattern Match
- 1959. Fewest Swaps to a Search Tree
- 1960. Numbers 1..n in Dictionary Order
- 1961. Longest Prefix Shared by Any Pair
- 1962. Banner Row Symbol
- 1963. Shortest Distinguishing Prefixes
- 1964. Editable Range Totals
- 1965. Live Minimum over Ranges
- 1966. Count Out-of-Order Pairs
- 1967. Quadtree Leaves for a Grid
- 1969. Best Short Downward Run
- 1970. Chain of Command Lengths
- 1975. Nodes k Above a Leaf
- 1976. Is the Mirror a BST in Reverse
- 1977. Same Values, Mirrored Rows
- 1978. Keep Filling a Complete Tree
- 1979. Rows of a BST Built by Insertions
- 1980. Kth Largest Value in a Plain Tree
- 1981. Smallest Subtree Covering a Range
- 1982. Delete a Whole Range from a BST
- 1983. Sum of Every Branch's Maximum
- 1984. Twin Subtrees Under One Node
- 1985. Most Distinct Values on a Branch
- 1987. BST Pairs Below a Bound
- 1988. Tree from a Depth Sequence
- 1990. Rebuild from a Dash-Indented Outline
- 1997. Balanced Shapes of Height h
- 2045. Subtrees with Totals in a Window
- 2046. Could This Be a BST's Row Order
- 2047. Sift a Complete Tree into a Max-Heap
- 2048. Neighbourhood Totals Within Two Steps
- 2049. Recolour into Alternating Colours
- 2050. Shortcuts from the Root
- 2051. Smallest Preorder by Child Swaps
- 2052. Ancestor Divides Descendant
- 2053. Longest-Match Tokenizer
- 2054. Prefix Pairs in a Word List
- 2055. Print a Tree on a Grid
- 2056. Subtrees Without Repeated Values
Hard
- 1763. Binary Tree Maximum Path Sum
- 1764. Binary Tree Cameras
- 1769. Insertion Orders Giving the Same BST
- 1986. Cheapest Clash-Free Painting
- 1989. Round-Trip a Tree Through Text
- 1991. Any-Shape Paths with a Target Sum
- 1992. Height After Removing a Subtree
- 1993. Richest BST Inside a Tree
- 1994. Fewest Leaf Flips to Change the Verdict
- 1995. Cheapest Search Tree for Known Frequencies
- 1996. Shapes of Exact Height
- 1998. Total Distance from Every Node
- 1999. Ancestor Jumps
- 2000. Many Shared-Ancestor Queries
- 2001. Subtree Sums with Edits
- 2002. Path Maximum with Edits
- 2003. Close Pairs in a Tree
- 2004. Nearest Lit Node Queries
- 2005. Longest Path with Changing Labels
- 2006. Coins at the Far Edges
- 2007. Paths Whose Ends Are the Peak
- 2008. Three-Way XOR Split
- 2009. Nearest Coprime Ancestor
- 2010. Where the Frog Lands
- 2011. Distinct Colours in Every Subtree
- 2012. Cut into One-Marked Pieces
- 2013. Most Pieces Divisible by k
- 2014. Smaller Descendants Count
- 2015. Fewest Road Flips from Each Town
- 2016. Best Connected Team of Size k
- 2017. Fewest Stations Within Reach
- 2018. Strongest XOR Path in a Weighted Tree
- 2019. Joining Two Parks with One Trail
- 2020. Smallest Missing Code in Each Subtree
- 2021. Best Trail Starting from Every Node
- 2022. Rotations in a Self-Balancing Tree
- 2023. Rank Tracker for a Live Stream
- 2024. Find Many Words in a Letter Grid
- 2025. Words Made of Other Words
- 2026. Watch a Character Stream for Words
- 2027. XOR Queries Under a Cap
- 2028. Pairs with XOR Inside a Window
- 2029. Lookup by Prefix and Suffix Together
- 2030. Prefix Popularity per Word
- 2031. Best Suffix Match for Each Query
- 2032. Smaller Values to the Right
- 2033. Big Inversions
- 2034. Range Raises and Range Totals
- 2035. Stacking Crates on a Shelf
- 2036. Editable Grid Totals
- 2037. Peak Overlap Bookings
- 2038. Climbs with Bounded Steps
- 2039. Tracked Intervals
- 2040. Cost of Building a Sorted Shelf
- 2041. Best Segment After Each Edit
- 2042. Triplets in the Same Order in Two Rankings
- 2043. Running Kth Smallest with Deletes
- 2058. Place k Calm Markers
- 2059. Count Above a Threshold in Ranges
- 2060. Points Inside Each Rectangle
- 2061. Separate the Rival Camps
- 2062. Distinct Team Structures
- 2063. Guesses About the Root
- 2064. Clusters Counted by Diameter
- 2065. Pruning Game on a Tree
- 2066. Diameter as the Tree Grows
- 2067. Palindrome-Ready Paths in a Lettered Tree
- 2068. Split into Small Teams
- 2069. Collect or Halve Down the Tree
- 2070. Sum of Path Maximums
- 2071. Two Separate Subtrees with the Strongest XOR
- 2072. Bookend Pairs
- 2073. Cheapest Way to Spell a Target
- 2074. Distinct Values in Each Range Query
- 2075. Longest Free Stretch After Each Booking
- 2076. Count the Longest Rising Picks
- 2077. Kth Lit Bulb After Toggles
- 2078. Largest Complete Subtree Inside
- 2079. Ways a Logic Expression Comes Out True