Unit IV · TreesData Structures

Unit IV · Part 1

Tree Basics

What a tree is, the vocabulary every later topic uses, and how a general tree is stored in memory.

Syllabus: Definition and terminology of trees.

1.1At a glance

A tree is a hierarchy: one item at the top (the root), and every other item hangs below exactly one parent.

Problem it solves
Stores data that is naturally nested (folders in folders, chapters in a book) and lets you reach an item by following one path down instead of scanning everything.
The rule
Exactly one root, exactly one parent for every other node, no cycles. So n nodes always have n − 1 edges.
Think of it as
A family tree, a company org chart, or the folder tree in your file explorer.
Use it when
Data has a parent-child relationship, or you need fast search, sorted order or priority.
Not the right tool when
Items have many-to-many links (roads between cities): that is a graph.
Edgesn − 1Pathsexactly one between any two nodesHeightbetween log n and n − 1
Used inFile systemsHTML DOMCompilersDatabase indexesOrg charts

NextBinary tree (at most 2 children)Alsom-way tree (many keys per node)All treesCompare them

1.2Definition

Definition (write this in the exam)

A tree is a finite set of one or more nodes such that (i) there is one specially designated node called the root, and (ii) the remaining nodes are partitioned into n ≥ 0 disjoint sets T1, T2, …, Tn, where each set is itself a tree. T1 … Tn are called the subtrees of the root.

The definition is recursive: a tree is a root plus smaller trees. That is why almost every tree algorithm is written with recursion. A tree is a non-linear, hierarchical data structure: one element can have many successors, but only one predecessor.

A tree with n nodes has exactly n − 1 edges, no cycles, and exactly one path between any two nodes.

Every node except the root has exactly one parent, and each parent link is one edge. So n nodes give n − 1 edges. If you add one more edge you create a cycle; if you remove one you split the tree in two.

StructureTree?Reason
A→B, A→C, C→DYesOne root, every other node has one parent
A→B, A→C, B→D, C→DNoD has two parents, so there are two paths from A to D. This is a graph.
A→B, B→C, C→ANoContains a cycle, and there is no root
A→B and separately C→DNoTwo roots. This is a forest (a set of disjoint trees).

Tree vs. graph, linear vs. non-linear

Arrays, stacks, queues and linked lists are linear: every element has at most one next element, so the data sits on a single line. A tree is non-linear: one node can lead to several nodes, so the data spreads out in levels. A tree is a special kind of graph.

TreeGraph
RootExactly one rootNo root
ParentsEach node (except the root) has exactly one parentA node can be connected to any number of nodes
CyclesNeverAllowed
EdgesExactly n − 1Any number, from 0 to n(n − 1)/2 (undirected)
Path between two nodesExactly oneZero, one or many
StructureHierarchical (levels)Network

1.3Terminology

Tap any node below. The panel shows every term for that node, so you can check your understanding on the same tree the exam will give you.

Convention used in these notes: level of the root = 0, and height is counted in edges (a leaf has height 0, an empty tree −1). Some textbooks start levels at 1 and count height in nodes. Either is accepted if you state your convention at the top of the answer.

TermDefinitionIn the tree above
NodeThe basic element of a tree. It stores a data item together with links (branches) to its children.13 nodes: A to M
RootThe unique node at the top of the tree that has no parent. Every other node can be reached from it by exactly one path.A
Edge (branch)The link that connects a parent node to one of its children. A tree with n nodes has exactly n − 1 edges.12 edges
ParentA node that has one or more nodes directly below it. If an edge goes from X down to Y, then X is the parent (predecessor) of Y.F is the parent of K and L
ChildA node that is directly below another node and connected to it by one edge. If X is the parent of Y, then Y is a child (successor) of X.K and L are children of F
SiblingsTwo or more nodes that have the same parent.H, I, J (children of D)
Leaf (terminal / external node)A node with no children, that is, a node whose degree is 0.E, K, L, G, M, I, J
Internal node (non-terminal)A node that has at least one child. The root is internal unless it is the only node.A, B, C, D, F, H
Degree of a nodeThe number of children of that node (the number of subtrees hanging from it).deg(D) = 3, deg(C) = 1, deg(E) = 0
Degree of a treeThe maximum degree of any node in the tree.3
LevelThe generation number of a node. The root is at level 0, and if a node is at level l, its children are at level l + 1.level(F) = 2
Depth of a nodeThe number of edges on the path from the root to that node. It equals the node's level.depth(K) = 3
Height of a nodeThe number of edges on the longest downward path from that node to a leaf. Every leaf has height 0.height(B) = 2
Height of the tree (depth of the tree)The height of the root, which is the same as the maximum level of any node. An empty tree has height −1.3
PathA sequence of nodes n1, n2, …, nk such that each ni is the parent of ni+1.A → B → F → K
Path lengthThe number of edges on a path, which is one less than the number of nodes on it.A → B → F → K has length 3
AncestorAny node on the path from the root to a given node, excluding the node itself. The parent, grandparent and so on up to the root.Ancestors of M: H, D, A
DescendantAny node that can be reached by going downward from a given node: its children, their children, and so on.Descendants of B: E, F, K, L
SubtreeA node together with all of its descendants. Each child of a node is the root of one subtree of that node.Subtree rooted at F: F, K, L
ForestA set of n ≥ 0 disjoint trees. Removing the root of a tree leaves a forest of its subtrees.Remove A → 3 trees rooted at B, C, D
Common mistake: Mixing up depth and height. Depth is measured down from the root (the root has depth 0). Height is measured up from the leaves (every leaf has height 0). The two are equal only for the tree as a whole.

1.4Representing a general tree in memory

A general tree allows any number of children, so a node cannot have a fixed number of pointer fields without waste. There are two standard ways to store it.

(a) Fixed k child pointers per node

Give each node k pointer fields, where k is the degree of the tree. With n nodes there are nk pointer fields, but only n − 1 are used (one per edge). So n(k − 1) + 1 fields hold NULL. For k = 3 and n = 13 that is 27 wasted fields out of 39.

(b) Left-child right-sibling (LCRS)

Every node keeps just two pointers: left → its first child and right → its next sibling. Any general tree becomes a binary tree this way. This is the reason we study binary trees in such detail: they can represent every tree.

struct gnode {
    char data;
    struct gnode *firstChild;    /* left pointer  */
    struct gnode *nextSibling;   /* right pointer */
};
Conversion rule: keep the edge from each parent to its left-most child, delete the parent's edges to all other children, and link the siblings left to right. Then rotate the picture 45° clockwise.

1.5How to read the pictures

The same drawing rules are used on every page, so learn them once here.

Binary trees

A circle is a node and the text inside is its key. A line is an edge: the parent is above, a left child is drawn lower-left and a right child lower-right. Nodes are placed left to right in in-order, so a BST reads sorted from left to right.

Multi-key nodes (m-way, B, B+)

A box with several keys is one node. Pointers leave from the gaps: the left edge is P0, the gap between key 1 and key 2 is P1, and so on. A small dot under a gap is an empty (NULL) pointer.

B+ trees

Grey boxes are index nodes (signposts only), white boxes are leaves (the real data), and the dashed arrows are the next-leaf links.

Small labels

A small number beside a node (+1, 0, −1) is its balance factor. Triangles T1–T4 are whole subtrees. Heaps show the array under the tree. Huffman trees write 0 on left edges and 1 on right edges.

Colours in every visualizer

current nodepath taken so farnew or movedchild, successor or siblingunbalanced, overflow or being deletedvisited or found

1.6Real-life applications

File systems

Every folder is a node and its files and sub-folders are its children. The drive (C:\ or /) is the root.

Why a tree: each file lives in exactly one folder, so the paths never loop.

Web pages (HTML DOM)

The browser turns every page into a tree of tags: <html> is the root, <body> its child, and so on down to each paragraph.

Why a tree: every tag is nested inside exactly one parent tag.

Compilers

Source code becomes a syntax tree; an expression like (a + b) * c becomes an expression tree.

Why a tree: operator precedence is stored in the shape itself.

Organisation charts

A company, a book, or a menu: each item sits under exactly one parent.

Why a tree: the hierarchy is the data.

Indexes, heaps, tries and Huffman codes are trees too, but each one adds a rule of its own. They are drawn on the family map, not repeated here.

1.7The family of trees

Every tree in this unit is a general tree with one extra rule added. Read the map top to bottom: each arrow names the rule that turns one tree into the next. Tap a box to open that part.

1.8Interview and viva questions

Q1Is every tree a graph? Is every graph a tree?

Every tree is a graph: a connected graph with no cycles. Not every graph is a tree: a graph may have cycles, may be disconnected, and has no root.

Q2What are the smallest and largest possible heights of a tree with n nodes?

Largest: n − 1, when the nodes form a chain. Smallest: 1 for any n ≥ 2 if a node may have any number of children (the root with n − 1 children). For a binary tree the smallest height is ⌈log2(n + 1)⌉ − 1.

Q3How do you store a tree whose nodes can have any number of children?

Use the left-child right-sibling form (two pointers per node: first child and next sibling), or give each node a dynamic list or array of children. The first turns any tree into a binary tree.

Q4Why are almost all tree algorithms written with recursion?

Because the definition is recursive: a tree is a root plus smaller trees. Solving the problem for the root usually means solving the same problem on each subtree and combining the answers.

Common mistakes in this part

  • Mixing up depth (counted down from the root) and height (counted up from the deepest leaf).
  • Calling a structure with a cycle, or a node with two parents, a tree. Check: n nodes must have exactly n − 1 edges.
  • Confusing the degree of a node (its children) with the degree of the tree (the maximum over all nodes).
  • Using level 1 for the root in one answer and level 0 in the next. Pick one convention and state it.

Key points to remember

  • A tree is a non-linear, hierarchical structure: one root, every other node has exactly one parent, no cycles.
  • n nodes ⇒ n − 1 edges, and exactly one path between any two nodes.
  • Degree counts children; depth/level counts edges down from the root; height counts edges up from the deepest leaf.
  • State your convention: root at level 0, height in edges (leaf = 0).
  • A general tree is stored as a binary tree using left-child, right-sibling.