Skip to content
CodeItRaw
Trees

Lesson 3/3

In some questions a node cannot decide by looking at its children alone; it needs information from above. Does some root-to-leaf path add up to the target? You hand each node "what is left by here" as a parameter; if at a leaf what is left is exactly the leaf's value, the path is found.

def has_path(node, left):
if node is None:
return False
if node.left is None and node.right is None:
return left == node.val
rest = left - node.val
return has_path(node.left, rest) or has_path(node.right, rest)
Because the path has to end at a leaf, the decision is made at the leaf, not at an empty node. or stops at the first path found; if the left side returns True the right is never looked at.

Checking a search tree works on the same idea: you hand each node the range its value must stay inside. Going left the upper bound becomes the node's value, going right the lower bound does. That way a node is compared not only with its parent but with every ancestor above it.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Counting Nodes

    Code reading · Review the AI

  2. 02

    Path Sum

    Function

  3. 03

    Is It a Search Tree?

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list