NeetCode 150, stage 7: Trees

← Linked List · All 150 problems · Tries →

A tree problem is a small question that each node answers for its own subtree. This stage trains recursion: a base case, one call for each child, and one line that combines the answers. It also trains closures, which let a recursive function in Go keep a result outside its return value.

Garden notes: the Go syntax for this stage.

Problems on this page

#ProblemLevelPatternTemplate
1226. Invert Binary TreeEasyRecursive DFS, swap the childrenA: DFS that returns a value
2104. Maximum Depth of Binary TreeEasyRecursive DFS that returns the heightA: DFS that returns a value
3543. Diameter of Binary TreeEasyDFS returns the height, records the diameterB: DFS that returns one value and records another
4110. Balanced Binary TreeEasyDFS returns the height, records the balanceB: DFS that returns one value and records another
5100. Same TreeEasyRecursive DFS on two treesA: DFS that returns a value
6572. Subtree of Another TreeEasyDFS with a same-tree testA: DFS that returns a value
7235. Lowest Common Ancestor of a Binary Search TreeMediumBST walk to the split pointE: BST walk that uses the order
8102. Binary Tree Level Order TraversalMediumBFS by levelD: BFS by level
9199. Binary Tree Right Side ViewMediumBFS by level, keep the last nodeD: BFS by level
101448. Count Good Nodes in Binary TreeMediumDFS that passes the path maximum downC: DFS that passes state down
1198. Validate Binary Search TreeMediumDFS that passes the limits downC: DFS that passes state down
12230. Kth Smallest Element in a BSTMediumInorder walk of a BST with a stackE: BST walk that uses the order
13105. Construct Binary Tree from Preorder and Inorder TraversalMediumPreorder cursor plus inorder index mapF: Preorder build with a cursor
14124. Binary Tree Maximum Path SumHardDFS returns one branch, records the full pathB: DFS that returns one value and records another
15297. Serialize and Deserialize Binary TreeHardPreorder DFS with null markersF: Preorder build with a cursor

Templates to memorize

Template A: DFS that returns a value

Signal

The answer for a tree comes from the answers for its two subtrees. For example: depth, “same tree”, “invert”, “is a subtree”.

// TEMPLATE A: DFS that returns a value. Each node answers for its own
// subtree.
func height(root *TreeNode) int {
    if root == nil { // 1. BASE CASE: an empty tree
        return 0
    }
    left := height(root.Left)   // 2. ASK the left subtree
    right := height(root.Right) // 3. ASK the right subtree
    return 1 + max(left, right) // 4. COMBINE the two answers with this node
}

The moves are BASE CASE, ASK LEFT, ASK RIGHT, COMBINE. Trust the recursive call: assume that it gives the correct answer for a subtree, and write only the combine step. Write the nil test first, or the code panics on an empty child.

Say it

“I solve it bottom-up. Each node asks its two children and combines their answers, so every node is visited once. That is O(n) time and O(h) space for the call stack.”

Template B: DFS that returns one value and records another

Signal

The answer can be anywhere in the tree, not only at the root: diameter, maximum path sum, “balanced at each node”. The value that a parent needs is different from the answer.

// TEMPLATE B: DFS that returns one value and records another.
// The return value goes to the parent. The closure variable keeps the best
// answer.
func longestPath(root *TreeNode) int {
    // the closure below can read and write best
    best := 0
    // declare first, so the function can call itself
    var dfs func(node *TreeNode) int
    dfs = func(node *TreeNode) int {
        if node == nil {
            return 0
        }
        left := dfs(node.Left)   // ASK
        right := dfs(node.Right) // ASK
        // RECORD: the path that turns at this node
        best = max(best, left+right)
        // RETURN: only one side continues to the parent
        return 1 + max(left, right)
    }
    dfs(root)
    return best
}

The moves are ASK LEFT, ASK RIGHT, RECORD, RETURN. The recorded value uses the two sides. The returned value uses only one side, because a path cannot go down two branches and also up to the parent. Declare the function variable with var before you assign it, or the closure cannot call itself.

Say it

“The helper returns the height, which is what the parent needs. On the way up it updates the best answer in a variable outside. One pass, O(n).”

Template C: DFS that passes state down

Signal

A node cannot decide alone. It needs a fact from its ancestors: the limits for a BST, the largest value on the path, the sum from the root.

// TEMPLATE C: DFS that passes state down. The parameter carries what the
// ancestors know.
// Here the state is the sum that is necessary below this node.
func hasPathSum(node *TreeNode, remaining int) bool {
    if node == nil { // BASE CASE
        return false
    }
    // UPDATE the state with this node
    remaining -= node.Val
    // USE the state: a leaf decides
    if node.Left == nil && node.Right == nil {
        return remaining == 0
    }
    // PASS DOWN: each child gets its own copy of the state.
    return hasPathSum(node.Left, remaining) || hasPathSum(node.Right, remaining)
}

The moves are BASE CASE, UPDATE or USE the state, PASS DOWN. The state is a parameter, and Go copies a parameter for each call. So a change for the left child does not reach the right child.

Say it

“I pass what the ancestors know down as a parameter, so each node decides in O(1). The total is O(n).”

Template D: BFS by level

Signal

The problem says level, row, “depth by depth”, “right side view” or the minimum number of steps.

// TEMPLATE D: BFS by level. One turn of the outer loop is one level of the
// tree.
func levels(root *TreeNode) [][]int {
    var res [][]int
    if root == nil {
        return res
    }
    queue := []*TreeNode{root}
    for len(queue) > 0 {
        size := len(queue) // 1. FREEZE: these nodes are exactly one level
        level := make([]int, 0, size)
        for i := 0; i < size; i++ {
            node := queue[0] // 2. POP from the front
            queue = queue[1:]
            level = append(level, node.Val)
            if node.Left != nil { // 3. PUSH the children: the next level
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        res = append(res, level)
    }
    return res
}

The moves are FREEZE the size of the queue, POP that number of nodes, PUSH their children. The frozen size is the number of nodes in the current level. Do not read len(queue) in the condition of the inner loop, because the queue grows inside that loop.

Say it

“I use a queue and process one level per loop. I read the queue size first, and that many nodes are exactly one level. It is O(n) time, and the queue holds at most one level.”

Template E: BST walk that uses the order

Signal

The tree is a binary search tree. The problem asks for a search, a lowest common ancestor, or the kth value in sorted order.

// TEMPLATE E: use the order of a BST: left subtree < node < right subtree.
// Tool 1: one comparison at each node chooses one side. Time O(h).
func search(root *TreeNode, target int) *TreeNode {
    node := root
    for node != nil && node.Val != target {
        if target < node.Val { // COMPARE, then GO to one side only
            node = node.Left
        } else {
            node = node.Right
        }
    }
    return node
}
 
// Tool 2: inorder (left, node, right) visits the values in sorted order.
func sortedValues(root *TreeNode) []int {
    var res []int
    stack := []*TreeNode{} // the nodes that wait for their visit
    node := root
    for node != nil || len(stack) > 0 {
        for node != nil { // 1. GO LEFT as far as possible
            stack = append(stack, node)
            node = node.Left
        }
        // 2. POP and VISIT: the smallest value that waits
        node = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        res = append(res, node.Val)
        node = node.Right // 3. GO RIGHT one step
    }
    return res
}

A BST gives two tools. One comparison at each node chooses one side, so a search costs O(h). An inorder walk visits the values in sorted order, so the kth node that you visit is the kth smallest. The moves of the inorder walk are GO LEFT, POP and VISIT, GO RIGHT.

Say it

“Because it is a BST, I compare with the node and go to one side only, so it is O(h). When I need sorted order, I do an inorder walk.”

Template F: Preorder build with a cursor

Signal

The problem asks you to build a tree from a sequence. The sequence is a preorder walk plus an inorder walk, or a string that your own code wrote.

// TEMPLATE F: build a tree from a preorder sequence with a cursor.
// "N" marks an empty child: "1,2,N,N,3,N,N" is the root 1 with the children
// 2 and 3.
func fromPreorder(tokens []string) *TreeNode {
    // CURSOR: the index of the next token. All the calls share it.
    next := 0
    var build func() *TreeNode
    build = func() *TreeNode {
        tok := tokens[next] // READ one token and move the cursor
        next++
        if tok == "N" { // EMPTY: this subtree has no nodes
            return nil
        }
        val, _ := strconv.Atoi(tok)
        node := &TreeNode{Val: val} // the ROOT comes first in preorder
        node.Left = build()         // then the full LEFT subtree
        node.Right = build()        // then the full RIGHT subtree
        return node
    }
    return build()
}

The moves are READ the root at the cursor, test for EMPTY, build LEFT, build RIGHT. All the calls share one cursor, and each call reads exactly the tokens of its subtree. Build the left subtree before the right subtree, because preorder gives it first.

Say it

“Preorder gives me the root first. I keep one index into the sequence, read the root, then build the left subtree and the right subtree recursively. Each node costs O(1).”

Mistakes in this stage

  • A closure that calls itself needs var dfs func(*TreeNode) int first, then dfs = func.... With dfs := func..., the name does not exist in the body.
  • node.Left.Val panics when node.Left is nil. Test for nil at the top of the function.
  • i < len(queue) in the inner loop of a BFS mixes two levels. Save size := len(queue) first.
  • A BST test that compares a node only with its two children is wrong. Each node must be inside the limits from all its ancestors.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

226. Invert Binary Tree

LeetCode 226 · Easy

104. Maximum Depth of Binary Tree

LeetCode 104 · Easy

543. Diameter of Binary Tree

LeetCode 543 · Easy

110. Balanced Binary Tree

LeetCode 110 · Easy

100. Same Tree

LeetCode 100 · Easy

572. Subtree of Another Tree

LeetCode 572 · Easy

235. Lowest Common Ancestor of a Binary Search Tree

LeetCode 235 · Medium

102. Binary Tree Level Order Traversal

LeetCode 102 · Medium

199. Binary Tree Right Side View

LeetCode 199 · Medium

1448. Count Good Nodes in Binary Tree

LeetCode 1448 · Medium

98. Validate Binary Search Tree

LeetCode 98 · Medium

230. Kth Smallest Element in a BST

LeetCode 230 · Medium

105. Construct Binary Tree from Preorder and Inorder Traversal

LeetCode 105 · Medium

124. Binary Tree Maximum Path Sum

LeetCode 124 · Hard

297. Serialize and Deserialize Binary Tree

LeetCode 297 · Hard


← Linked List · All 150 problems · Tries →