Attic
DSATrees

Overview

Hierarchical data structures, binary tree classifications, node definitions, and complexity properties

A Tree is a non-linear, hierarchical data structure composed of nodes connected by directed or undirected edges. Unlike linear structures (arrays, linked lists, stacks, and queues) where elements are traversed sequentially, trees organize data in parent-child hierarchies.


Tree Terminology

TermDefinition
RootThe topmost node of the tree with no parent.
EdgeThe link or pointer connecting a parent node to its child.
Parent & ChildA node directly above another is its parent; nodes directly below are its children.
Leaf (External Node)A node that has no children (both left and right pointers are null).
Internal NodeA node with at least one non-null child.
Depth of a NodeThe number of edges along the path from the root to that node (root has depth 0).
Height of a NodeThe number of edges on the longest downward path from that node to a leaf.
Height of a TreeThe height of the root node (i.e. length of the longest root-to-leaf path).
SubtreeAny node together with all its descendants.

Java TreeNode Representation

In Java, binary trees are typically modeled using reference-linked objects:

TreeNode.java
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

Memory Overhead: Each TreeNode object incurs object header overhead plus two 64-bit object references (left and right). For n nodes, there are exactly n + 1 null pointers across all leaf and single-child nodes.


Binary Tree Classifications

ClassificationStructural InvariantPractical Significance
Full (Strict) Binary TreeEvery node has either 0 or 2 children. No node has exactly 1 child.Used in Huffman coding and compression trees.
Complete Binary TreeAll levels are completely filled except possibly the last, which is filled from left to right.Foundation for Binary Heaps (PriorityQueue), allowing flat array storage without pointers.
Perfect Binary TreeAll internal nodes have 2 children, and all leaves reside on the exact same level.Contains exactly 2^(h+1) - 1 total nodes where h is height.
Balanced Binary TreeFor every node, the height difference between left and right subtrees is <= 1.Guarantees worst-case O(log n) search, insert, and delete.
Degenerate (Skewed) TreeEvery internal node has only 1 child, degrading into a single chain.Degrades search operations to linear O(n) time.

Mathematical Properties of Binary Trees


Detailed Guides

On this page