Skip to content

7.1   Binary Tree

A binary tree is a non-linear data structure that represents the derivation relationship between "ancestors" and "descendants" and embodies the divide-and-conquer logic of "one divides into two". Similar to a linked list, the basic unit of a binary tree is a node, and each node contains a value, a reference to its left child node, and a reference to its right child node.

class TreeNode:
    """Binary tree node"""
    def __init__(self, val: int):
        self.val: int = val                # Node value
        self.left: TreeNode | None = None  # Reference to left child node
        self.right: TreeNode | None = None # Reference to right child node
/* Binary tree node */
struct TreeNode {
    int val;          // Node value
    TreeNode *left;   // Pointer to left child node
    TreeNode *right;  // Pointer to right child node
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
/* Binary tree node */
class TreeNode {
    int val;         // Node value
    TreeNode left;   // Reference to left child node
    TreeNode right;  // Reference to right child node
    TreeNode(int x) { val = x; }
}
/* Binary tree node */
class TreeNode(int? x) {
    public int? val = x;    // Node value
    public TreeNode? left;  // Reference to left child node
    public TreeNode? right; // Reference to right child node
}
/* Binary tree node */
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}
/* Constructor */
func NewTreeNode(v int) *TreeNode {
    return &TreeNode{
        Left:  nil, // Pointer to left child node
        Right: nil, // Pointer to right child node
        Val:   v,   // Node value
    }
}
/* Binary tree node */
class TreeNode {
    var val: Int // Node value
    var left: TreeNode? // Reference to left child node
    var right: TreeNode? // Reference to right child node

    init(x: Int) {
        val = x
    }
}
/* Binary tree node */
class TreeNode {
    val; // Node value
    left; // Pointer to left child node
    right; // Pointer to right child node
    constructor(val, left, right) {
        this.val = val === undefined ? 0 : val;
        this.left = left === undefined ? null : left;
        this.right = right === undefined ? null : right;
    }
}
/* Binary tree node */
class TreeNode {
    val: number;
    left: TreeNode | null;
    right: TreeNode | null;

    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = val === undefined ? 0 : val; // Node value
        this.left = left === undefined ? null : left; // Reference to left child node
        this.right = right === undefined ? null : right; // Reference to right child node
    }
}
/* Binary tree node */
class TreeNode {
  int val;         // Node value
  TreeNode? left;  // Reference to left child node
  TreeNode? right; // Reference to right child node
  TreeNode(this.val, [this.left, this.right]);
}
use std::rc::Rc;
use std::cell::RefCell;

/* Binary tree node */
struct TreeNode {
    val: i32,                               // Node value
    left: Option<Rc<RefCell<TreeNode>>>,    // Reference to left child node
    right: Option<Rc<RefCell<TreeNode>>>,   // Reference to right child node
}

impl TreeNode {
    /* Constructor */
    fn new(val: i32) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Self {
            val,
            left: None,
            right: None
        }))
    }
}
/* Binary tree node */
typedef struct TreeNode {
    int val;                // Node value
    int height;             // Node height
    struct TreeNode *left;  // Pointer to left child node
    struct TreeNode *right; // Pointer to right child node
} TreeNode;

/* Constructor */
TreeNode *newTreeNode(int val) {
    TreeNode *node;

    node = (TreeNode *)malloc(sizeof(TreeNode));
    node->val = val;
    node->height = 0;
    node->left = NULL;
    node->right = NULL;
    return node;
}
/* Binary tree node */
class TreeNode(val _val: Int) {  // Node value
    val left: TreeNode? = null   // Reference to left child node
    val right: TreeNode? = null  // Reference to right child node
}
### Binary tree node class ###
class TreeNode
  attr_accessor :val    # Node value
  attr_accessor :left   # Reference to left child node
  attr_accessor :right  # Reference to right child node

  def initialize(val)
    @val = val
  end
end

Each node has two references (pointers), pointing respectively to the left-child node and right-child node. This node is called the parent node of these two child nodes. When given a node of a binary tree, we call the tree formed by this node's left child and all nodes below it the left subtree of this node. Similarly, the right subtree can be defined.

In a binary tree, except leaf nodes, all other nodes contain child nodes and non-empty subtrees. As shown in Figure 7-1, if "Node 2" is regarded as a parent node, its left and right child nodes are "Node 4" and "Node 5" respectively. The left subtree is formed by "Node 4" and all nodes beneath it, while the right subtree is formed by "Node 5" and all nodes beneath it.

Parent Node, child Node, subtree

Figure 7-1   Parent Node, child Node, subtree

7.1.1   Common Terminology of Binary Trees

The commonly used terminology of binary trees is shown in Figure 7-2.

  • Root node: The node at the top level of a binary tree, which does not have a parent node.
  • Leaf node: A node that does not have any child nodes, with both of its pointers pointing to None.
  • Edge: A line segment that connects two nodes, representing a reference (pointer) between the nodes.
  • The level of a node: It increases from top to bottom, with the root node being at level 1.
  • The degree of a node: The number of child nodes that a node has. In a binary tree, the degree can be 0, 1, or 2.
  • The height of a binary tree: The number of edges from the root node to the farthest leaf node.
  • The depth of a node: The number of edges from the root node to the node.
  • The height of a node: The number of edges from the farthest leaf node to the node.

Common Terminology of Binary Trees

Figure 7-2   Common Terminology of Binary Trees

Tip

Please note that we usually define "height" and "depth" as "the number of edges traversed", but some questions or textbooks may define them as "the number of nodes traversed". In this case, both height and depth need to be incremented by 1.

7.1.2   Basic Operations of Binary Trees

1.   Initializing a Binary Tree

Similar to a linked list, the initialization of a binary tree involves first creating the nodes and then establishing the references (pointers) between them.

binary_tree.py
# Initializing a binary tree
# Initializing nodes
n1 = TreeNode(val=1)
n2 = TreeNode(val=2)
n3 = TreeNode(val=3)
n4 = TreeNode(val=4)
n5 = TreeNode(val=5)
# Linking references (pointers) between nodes
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
binary_tree.cpp
/* Initializing a binary tree */
// Initializing nodes
TreeNode* n1 = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(4);
TreeNode* n5 = new TreeNode(5);
// Linking references (pointers) between nodes
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
binary_tree.java
// Initializing nodes
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// Linking references (pointers) between nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.cs
/* Initializing a binary tree */
// Initializing nodes
TreeNode n1 = new(1);
TreeNode n2 = new(2);
TreeNode n3 = new(3);
TreeNode n4 = new(4);
TreeNode n5 = new(5);
// Linking references (pointers) between nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.go
/* Initializing a binary tree */
// Initializing nodes
n1 := NewTreeNode(1)
n2 := NewTreeNode(2)
n3 := NewTreeNode(3)
n4 := NewTreeNode(4)
n5 := NewTreeNode(5)
// Linking references (pointers) between nodes
n1.Left = n2
n1.Right = n3
n2.Left = n4
n2.Right = n5
binary_tree.swift
// Initializing nodes
let n1 = TreeNode(x: 1)
let n2 = TreeNode(x: 2)
let n3 = TreeNode(x: 3)
let n4 = TreeNode(x: 4)
let n5 = TreeNode(x: 5)
// Linking references (pointers) between nodes
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
binary_tree.js
/* Initializing a binary tree */
// Initializing nodes
let n1 = new TreeNode(1),
    n2 = new TreeNode(2),
    n3 = new TreeNode(3),
    n4 = new TreeNode(4),
    n5 = new TreeNode(5);
// Linking references (pointers) between nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.ts
/* Initializing a binary tree */
// Initializing nodes
let n1 = new TreeNode(1),
    n2 = new TreeNode(2),
    n3 = new TreeNode(3),
    n4 = new TreeNode(4),
    n5 = new TreeNode(5);
// Linking references (pointers) between nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.dart
/* Initializing a binary tree */
// Initializing nodes
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// Linking references (pointers) between nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.rs
// Initializing nodes
let n1 = TreeNode::new(1);
let n2 = TreeNode::new(2);
let n3 = TreeNode::new(3);
let n4 = TreeNode::new(4);
let n5 = TreeNode::new(5);
// Linking references (pointers) between nodes
n1.borrow_mut().left = Some(n2.clone());
n1.borrow_mut().right = Some(n3);
n2.borrow_mut().left = Some(n4);
n2.borrow_mut().right = Some(n5);
binary_tree.c
/* Initializing a binary tree */
// Initializing nodes
TreeNode *n1 = newTreeNode(1);
TreeNode *n2 = newTreeNode(2);
TreeNode *n3 = newTreeNode(3);
TreeNode *n4 = newTreeNode(4);
TreeNode *n5 = newTreeNode(5);
// Linking references (pointers) between nodes
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
binary_tree.kt
// Initializing nodes
val n1 = TreeNode(1)
val n2 = TreeNode(2)
val n3 = TreeNode(3)
val n4 = TreeNode(4)
val n5 = TreeNode(5)
// Linking references (pointers) between nodes
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
binary_tree.rb
# Initializing a binary tree
# Initializing nodes
n1 = TreeNode.new(1)
n2 = TreeNode.new(2)
n3 = TreeNode.new(3)
n4 = TreeNode.new(4)
n5 = TreeNode.new(5)
# Linking references (pointers) between nodes
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
Code Visualization

2.   Inserting and Removing Nodes

Similar to a linked list, inserting and removing nodes in a binary tree can be achieved by modifying pointers. Figure 7-3 provides an example.

Inserting and removing nodes in a binary tree

Figure 7-3   Inserting and removing nodes in a binary tree

binary_tree.py
# Inserting and removing nodes
p = TreeNode(0)
# Inserting node P between n1 -> n2
n1.left = p
p.left = n2
# Removing node P
n1.left = n2
binary_tree.cpp
/* Inserting and removing nodes */
TreeNode* P = new TreeNode(0);
// Inserting node P between n1 and n2
n1->left = P;
P->left = n2;
// Removing node P
n1->left = n2;
binary_tree.java
TreeNode P = new TreeNode(0);
// Inserting node P between n1 and n2
n1.left = P;
P.left = n2;
// Removing node P
n1.left = n2;
binary_tree.cs
/* Inserting and removing nodes */
TreeNode P = new(0);
// Inserting node P between n1 and n2
n1.left = P;
P.left = n2;
// Removing node P
n1.left = n2;
binary_tree.go
/* Inserting and removing nodes */
// Inserting node P between n1 and n2
p := NewTreeNode(0)
n1.Left = p
p.Left = n2
// Removing node P
n1.Left = n2
binary_tree.swift
let P = TreeNode(x: 0)
// Inserting node P between n1 and n2
n1.left = P
P.left = n2
// Removing node P
n1.left = n2
binary_tree.js
/* Inserting and removing nodes */
let P = new TreeNode(0);
// Inserting node P between n1 and n2
n1.left = P;
P.left = n2;
// Removing node P
n1.left = n2;
binary_tree.ts
/* Inserting and removing nodes */
const P = new TreeNode(0);
// Inserting node P between n1 and n2
n1.left = P;
P.left = n2;
// Removing node P
n1.left = n2;
binary_tree.dart
/* Inserting and removing nodes */
TreeNode P = new TreeNode(0);
// Inserting node P between n1 and n2
n1.left = P;
P.left = n2;
// Removing node P
n1.left = n2;
binary_tree.rs
let p = TreeNode::new(0);
// Inserting node P between n1 and n2
n1.borrow_mut().left = Some(p.clone());
p.borrow_mut().left = Some(n2.clone());
// Removing node P
n1.borrow_mut().left = Some(n2);
binary_tree.c
/* Inserting and removing nodes */
TreeNode *P = newTreeNode(0);
// Inserting node P between n1 and n2
n1->left = P;
P->left = n2;
// Removing node P
n1->left = n2;
binary_tree.kt
val P = TreeNode(0)
// Inserting node P between n1 and n2
n1.left = P
P.left = n2
// Removing node P
n1.left = n2
binary_tree.rb
# Inserting and removing nodes
_p = TreeNode.new(0)
# Inserting node _p between n1 and n2
n1.left = _p
_p.left = n2
# Removing node _p
n1.left = n2
Code Visualization

Tip

It should be noted that inserting nodes may change the original logical structure of the binary tree, while removing nodes typically involves removing the node and all its subtrees. Therefore, in a binary tree, insertion and removal are usually performed through a set of operations to achieve meaningful outcomes.

7.1.3   Common Types of Binary Trees

1.   Perfect Binary Tree

As shown in Figure 7-4, a perfect binary tree has all levels completely filled with nodes. In a perfect binary tree, leaf nodes have a degree of \(0\), while all other nodes have a degree of \(2\). If the tree height is \(h\), the total number of nodes is \(2^{h+1} - 1\), exhibiting a standard exponential relationship that reflects the common phenomenon of cell division in nature.

Tip

Please note that in the Chinese community, a perfect binary tree is often referred to as a full binary tree.

Perfect binary tree

Figure 7-4   Perfect binary tree

2.   Complete Binary Tree

As shown in Figure 7-5, a complete binary tree only allows the bottom level to be incompletely filled, and the nodes at the bottom level must be filled continuously from left to right. Note that a perfect binary tree is also a complete binary tree.

Complete binary tree

Figure 7-5   Complete binary tree

3.   Full Binary Tree

As shown in Figure 7-6, in a full binary tree, all nodes except leaf nodes have two child nodes.

Full binary tree

Figure 7-6   Full binary tree

4.   Balanced Binary Tree

As shown in Figure 7-7, in a balanced binary tree, the absolute difference between the height of the left and right subtrees of any node does not exceed 1.

Balanced binary tree

Figure 7-7   Balanced binary tree

7.1.4   Degeneration of Binary Trees

Figure 7-8 shows the ideal and degenerate structures of binary trees. When every level of a binary tree is filled, it reaches the "perfect binary tree" state; when all nodes are biased toward one side, the binary tree degenerates into a "linked list".

  • A perfect binary tree is the ideal case, fully leveraging the "divide and conquer" advantage of binary trees.
  • A linked list represents the other extreme, where all operations become linear operations with time complexity degrading to \(O(n)\).

The Best and Worst Structures of Binary Trees

Figure 7-8   The Best and Worst Structures of Binary Trees

As shown in Table 7-1, in the best and worst structures, the binary tree achieves either maximum or minimum values for leaf node count, total number of nodes, and height.

Table 7-1   The Best and Worst Structures of Binary Trees

Perfect binary tree Linked list
Number of nodes at level \(i\) \(2^{i-1}\) \(1\)
Number of leaf nodes in a tree with height \(h\) \(2^h\) \(1\)
Total number of nodes in a tree with height \(h\) \(2^{h+1} - 1\) \(h + 1\)
Height of a tree with \(n\) total nodes \(\log_2 (n+1) - 1\) \(n - 1\)
Feel free to drop your insights, questions or suggestions