What is Binary Tree Foundation
A binary tree is a root with at most two children, called left and right. A node with no children is a leaf. The picture builds one small tree so those names stay attached to the nodes.
root 1 left 2, right 3 2 has left child 4
Approach
Read the tree from the root downward. Every node except the root has one parent. The left child is drawn on the left, the right child on the right.
Level order lists the root, then the next level left to right. A -1 in that list is a missing child, not a node.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Build | O(n) | Each value in the level-order list becomes one node or one missing child. |
| Height | O(n) | Every node is visited once to find the deepest leaf. |
Implementation
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right