Builds onRecursion and the call stack
01The idea
A tree is a set of nodes joined by links, with no loops. One node at the top is the root. Every other node has exactly one parent. In a binary tree, each node has at most two children, called left and right.
A few words come up all the time:
- A leaf is a node with no children.
- The depth of a node is the number of links from the root down to it. The root has depth 0.
- The height of a tree is the largest depth of any node.
- A subtree is a node together with everything below it.
Each child is the root of its own smaller tree. So most tree code is recursive, with the same three parts each time:
- If the node is None, return the answer for an empty tree.
- Call the function on the left subtree and on the right subtree to get their answers.
- Combine the two answers with the node's own value.
You hold a tree by its root, like a linked list by its head. In Python a node has val, left and right. Missing children are None.
02How to spot it
You will meet trees when:
- the input is a
TreeNoderoot. Examples write the tree in level order, such as[5, 3, 8, null, 4] - the data has parents and children: folders, company charts, comment threads
- the question is about the whole tree, and the answer for a node depends on the answers for its children
Level order lists the nodes row by row, from left to right. null marks a missing child. Each node takes the next two entries in the list as its children.
A tree with n nodes has n - 1 links. Its height can be as small as about log₂ n when it is balanced, or as large as n - 1 when every node has one child. Recursion depth follows the height, so a tall tree means a deep stack.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue