Binary Tree

Binary Tree Foundation Visualizer

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.

Root, parent, childThe root is the only node with no parent. Following a child pointer moves one level down.
LeafA leaf has neither a left child nor a right child. Paths that the later problems talk about end at a leaf.

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

A tree growing from the root
root has no parent
each node has a left and a right
a missing child is null
a leaf has two null children
level order reads one row at a time
Step 0/0 Answer —

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

PieceCostWhy
BuildO(n)Each value in the level-order list becomes one node or one missing child.
HeightO(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