CodeGround
DashboardProblemsInterviewsAssessmentsCourses
CodeGround
DashboardProblemsInterviewsAssessmentsCourses
The Technical Interview Course

0 of 170 lessons complete

  • Recursion, properly
  • The tree recursion template
  • Combining what the children return
  • A recursion that calls another recursion
  • Computing once instead of at every node
  • Return one thing, update another
  • Going across instead of down
  • Carrying information down the tree
  • Search trees and the ordering you can exploit
  • Rebuilding a tree from its traversals
  • The two-quantity pattern at full strength
  • Writing a tree down and reading it back
  • Retrieval: which traversal, which direction?

Recursion and Trees

70 / 170

Recursion and Trees/Lesson 3 of 13·About 42 min

Combining what the children return

Measuring a tree, and walking two trees in step.

Key idea

Measuring downward

Some measurements are about how far the tree extends. The pattern is the same template, with a combination that takes the larger or smaller of the two children's answers and adds the current node.

1class T:2    def __init__(self, val, left=None, right=None):3        self.val, self.left, self.right = val, left, right4 5def longest_run_down(node, value):6    """Longest downward path of nodes all holding this value."""7    if node is None or node.val != value:8        return 09    return 1 + max(longest_run_down(node.left, value),10                   longest_run_down(node.right, value))11 12tree = T(7, T(7, T(7)), T(3))13print(longest_run_down(tree, 7))

Key idea

Walking two trees at once

The second kind of combination takes two trees and recurses on both in step: left against left, right against right. The base cases multiply, and getting them right is the whole difficulty.

There are three: both empty, exactly one empty, and both present. The middle case is the one people forget, and it is what stops the recursion from raising on a missing child.

1class T:2    def __init__(self, val, left=None, right=None):3        self.val, self.left, self.right = val, left, right4 5def same_shape(a, b):6    """Ignores values, compares structure only."""7    if a is None and b is None:8        return True9    if a is None or b is None:10        return False11    return same_shape(a.left, b.left) and same_shape(a.right, b.right)12 13print(same_shape(T(1, T(2)), T(9, T(8))))14print(same_shape(T(1, T(2)), T(1, None, T(2))))

Gotcha

The order of the two base cases matters

Check both-empty first, then either-empty. Reversed, the either-empty test fires when both are None and wrongly reports a mismatch.

This is the same left-to-right evaluation care as the stack guards in U4, and the same fix: order the conditions so the more specific one is tested first.

Tip

The second example is worth studying

T(1, T(2)) has a left child. T(1, None, T(2)) has a right child. Both hold the same values and both have two nodes, and they are different trees.

Any function comparing two trees has to compare structure, not just contents, and pairing left with left and right with right is what does that. Comparing left against right somewhere by accident produces a function that reports mirrored trees as identical.

What comes next

The two problems below are these two shapes exactly. One measures how deep the tree goes, the other compares two trees node by node.

Both are short. Get the base cases right and there is nothing else to them, which is why they arrive here rather than later.

Quick check· 5 min

How many base cases?

You are writing a function that compares two trees for equality of both structure and values. How many base cases does it need before the recursive step?

Problem· 12 min

Maximum Depth Of Binary Tree

Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.

Problem· 14 min

Same Tree

Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.

PreviousThe tree recursion template
NextA recursion that calls another recursion

0 of 4 parts complete