Problems on trees and grids
After this: Find the maximum depth of a tree with recursion and count the islands in a grid.
On this page · 4 sections · 3 checks
A linked node has one next. A tree node has two children, and a cell in a grid has four neighbours. With more than one way to go, a loop is no longer enough to visit everything. Recursion handles it: a function that calls itself once for each way to go. This lesson works one problem on a tree and one on a grid, and both are solved that way.
8. Maximum depth of a binary tree
Here, the tree node class is called TreeNode, with value, left and right. The binary-trees tutorial called it Node, but this tutorial already has a Node for linked lists, so the tree one gets its own name.
Pattern: recursion. The depth of an empty tree is 0. The depth of any other tree is 1, for its root, plus the depth of its deeper child. Each call asks its two children and adds one.
class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right
def max_depth(root): if root is None: return 0 return 1 + max(max_depth(root.left), max_depth(root.right))class TreeNode { int value; TreeNode left, right;
TreeNode(int value) { this.value = value; } TreeNode(int value, TreeNode left, TreeNode right) { this.value = value; this.left = left; this.right = right; }}
static int maxDepth(TreeNode root) { if (root == null) { return 0; } return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));}Pinned example. The tree below has 8 at the root. 8 has children 3 and 10; 3 has 1 and 6; 6 has 4 and 7; 10 has one child on the right, 14. The longest path is 8 → 3 → 6 → 4, so the answer is 4. An empty tree gives 0, and a single node gives 1.
The tree visualizer measures height in links, not nodes, so it shows 3 for this tree, while maximum depth counts nodes and is 4: depth in nodes = height in links + 1.
- Measure the heightMeasure the height. This tree counts links, not nodes. Go to the last step to read the answer.
Run an operation to begin.
Cost. O(n) time: each node is asked once. Extra memory: one call frame for each level of the path being followed, so it grows with the height of the tree. A tall, thin tree needs a lot of frames, as Depth, and when to loop instead showed.
9. Number of islands
Pattern: a depth-first search from each land cell not yet seen. Go through the grid row by row. At a land cell not seen yet, you have found a new island: add 1. Then mark that whole island as seen, so that none of its other cells is counted again. A does the marking: from one cell, visit a neighbour, then its neighbour, as far as possible. You met it in Depth-first search, as deep as possible; a grid is a graph whose nodes are cells.
sink does the marking. It is an inner function, so it can read grid and seen without being given them.It is a separate static method, so it takes grid and seen as arguments. In Java, seen is a boolean[][]: one true or false for each cell. It returns at once if the cell is off the grid, is water, or is already seen. Otherwise it marks the cell and calls itself on the four neighbours.
- Run the programRun it and step through. Watch count and seen. Each time count goes up, sink opens a frame and marks every land cell of that island.
def count_islands(grid): rows = len(grid) cols = len(grid[0]) if grid else 0 seen = set() def sink(r, c): if r < 0 or r >= rows or c < 0 or c >= cols: return if grid[r][c] != "1" or (r, c) in seen: return seen.add((r, c)) sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1) count = 0 for r in range(rows): for c in range(cols): if grid[r][c] == "1" and (r, c) not in seen: count += 1 sink(r, c) return count
print(count_islands(["110", "010", "001"]))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Follow the grid 110 / 010 / 001:
- The loop meets (0, 0), land and not seen.
countbecomes 1, andsinkmarks (0, 0), then (0, 1), then (1, 1). - The loop goes on. (0, 1) and (1, 1) are already seen, and the rest are water, until (2, 2).
- (2, 2) is land and not seen: it touches (1, 1) only at a corner.
countbecomes 2, andsinkmarks it.
The answer is 2. The 4 × 5 grid 11010 / 10010 / 00100 / 00011 gives 4, and is too long to step through, so it is in the run block below. A grid of water gives 0, and so does an empty grid.
Cost. O(rows × cols) time: the loop visits each cell once, and sink marks each land cell once. Extra memory: also O(rows × cols), for seen and, on a grid that is all land, for the call frames.
Run it
Check yourself
A map is a grid of land and water cells. Land cells that touch up, down, left or right belong to the same island. Which pattern counts the islands?
A tree with a single node. What does this print?
class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right
def max_depth(root): if root is None: return 0 return 1 + max(max_depth(root.left), max_depth(root.right))
print(max_depth(TreeNode(5)))class TreeNode { int value; TreeNode left, right;
TreeNode(int value) { this.value = value; } TreeNode(int value, TreeNode left, TreeNode right) { this.value = value; this.left = left; this.right = right; }}
public class Main { static int maxDepth(TreeNode root) { if (root == null) { return 0; } return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }
public static void main(String[] args) { System.out.println(maxDepth(new TreeNode(5))); }}The grid is ["10", "01"]: land at the top left and at the bottom right, touching only at a corner. What does count_islandscountIslands return?
- Find the maximum depth of a tree with recursion: an empty tree is 0, any other tree is 1 plus the depth of its deeper child.
- Say that maximum depth counts nodes while the tree visualizer's height counts links, so depth is height plus 1.
- Count islands by going through the grid and starting a depth-first search at each land cell not seen yet.
- Say why cells that touch only at a corner are separate islands, and why recursion can run out of frames on a very large input.