Trees - Definitions and Properties
In questa pagina 9
A tree is a collection of nodes organised in a hierarchical structure that unfolds from a single node, the root, through parent-child relationships. The parent-child links are a minimal set of links connecting all nodes. A list is the extreme case of a tree whose hierarchy is linear.
Uses: data structures (maps, priority queues), file systems, communication networks, recursion trees in the analysis of algorithms, Huffman codes, decision trees in machine learning, phylogenetic trees in biology.
Rooted tree
A rooted tree is a collection of nodes that, if not empty, satisfies:
- there is a special node (the root);
- every , , has exactly one parent ( is a child of );
- from every , by repeatedly moving to the parent, we eventually reach (every node descends from the root).
The third condition is missing in the textbook. Without it, could be the parent of and the parent of : conditions 1 and 2 hold, but that is a forest of trees, not a single tree.
Terminology
| term | definition |
|---|---|
| ancestor | is an ancestor of if or is an ancestor of the parent of |
| descendant | is a descendant of if is an ancestor of |
| interior (internal) node | node with at least 1 child |
| external node (leaf) | node with no children |
| subtree rooted at | = the tree made of all descendants of |
| ordered tree | for every internal node a linear order is defined among its children (e.g. left to right) |
Note that a node is an ancestor (and a descendant) of itself.
A root: A
/ | \ interior: A, B, D
B C D leaves: E, F, C, G
/ \ \ T_B = {B, E, F}
E F GRecursive definition
A non-empty rooted tree can be partitioned as where is the root with children and each is a non-empty tree with root (that is, ). For , contains only .
Depth, level, height
Depth of a node in :
- , or equivalently
- , and otherwise.
Level of : the set of nodes of depth , for .
Height of a node in (recursive):
- if is a leaf;
- otherwise.
Height of the tree: . The height of a node is the maximum distance from it to a descendant leaf.
Depth is the distance from the root, height is the distance from the farthest leaf.
Example on the tree above: , or . , .
depth node (height)
0 A (2)
1 B (1) C (0) D (1)
2 E (0) F (0) G (0)Proposition 8.3
For every tree : . The height of a tree is the depth of its deepest leaf.
Proof by induction on the number of nodes of .
- Base case : is only the root , which is a leaf. Height . ( would be the empty tree.)
- Inductive step: assume the property for every tree with nodes, , and take a tree with nodes. Then has a root and subtrees rooted at the children of , each with at most nodes. Then:
counts the ancestors of up to ; adding 1 adds the root, giving . The leaves of are exactly the leaves of the subtrees , so the two maxima merge into a maximum over all leaves of .
Tree interface and linked implementation
Two Java interfaces are needed first:
public interface Iterator<E> {
/** Returns true if the scan of the collection is not over */
boolean hasNext();
/** Returns the next element in the collection */
E next();
}
public interface Iterable<E> {
/** Returns an iterator for the collection */
Iterator<E> iterator();
}Iterator: a cursor that enumerates the elements of a collection, in one direction only; the order depends on the implementation.Iterable: a collection that makes an iterator available.
The tree follows the idea of position-based lists: each node is a position (interface Position<E>, method getElement()) giving access to its element and links.
- Node (
Position<E>): stores a reference to the element and pointers to its parent and to its children (kept in an auxiliary data structure). - Tree (
Tree<E>): stores a reference to the root and the total number of nodes (numElements).
public interface Tree<E> extends Iterable<E> {
/** Returns the number of positions in the tree */
int size();
/** Returns true if the tree contains no positions */
boolean isEmpty();
/** Returns the Position of the root (or null if empty) */
Position<E> root();
/** Returns the Position of p's parent (or null if p is the root) */
Position<E> parent(Position<E> p);
/** Returns an iterable containing p's children */
Iterable<Position<E>> children(Position<E> p);
/** Returns the number of children of p */
int numChildren(Position<E> p);
/** Returns true if p is internal */
boolean isInternal(Position<E> p);
/** Returns true if p is external (leaf) */
boolean isExternal(Position<E> p);
/** Returns true if p is root */
boolean isRoot(Position<E> p);
/** Returns an iterator to all elements in the tree */
Iterator<E> iterator();
/** Returns an iterable containing all positions in the tree */
Iterable<Position<E>> positions();
}root()is the only direct access: every other node is reached by navigation (parent,children). There is no random access.children(p)returns an iterable of positions; the order of enumeration depends on the implementation.- Since
TreeextendsIterable, it provides an iterator over its elements;positions()enumerates nodes instead of the elements they store. - Cost assumption: all methods are , except
children,iteratorandpositions; the children of a node can be enumerated in time proportional to their number, and retrieving the next child takes .
In the pseudocode below the tree is passed explicitly, for clarity.
Computing the depth of a node
Recursive
Algorithm: depth(T, v)
Input: v in T
Output: depth of v in T
if (T.isRoot(v)) then return 0;
else return 1 + depth(T, T.parent(v));Direct translation of the recursive definition.
Complexity. Let . The recursion tree is a chain with nodes (one call per ancestor of , including the root, the base case). Each call costs (isRoot is , the return does a constant number of operations). Total:
- The is kept to handle : calling it on the root still costs a constant, not . (Often written , meaning .)
- For a fixed there is no worst case: gives exactly the number of calls. Shallow nodes are fast, deep nodes slow.
- In terms of the tree size : , since ; and in a degenerate tree (a chain of nodes) with the last node the cost is proportional to . So the worst case over nodes is .
- Choosing the instance size, local () or global (), gives a more or less detailed analysis.
Iterative
Algorithm: iter-depth(T, v)
Input: v in T
Output: depth of v in T
depth <- 0;
while (!T.isRoot(v)) do
v <- T.parent(v);
depth <- depth + 1;
return depth;Move up from , adding 1 at each step. Constant work outside the loop, constant work per iteration, exactly iterations: , or equivalently in the worst case.
Computing the height of a node
Algorithm: height(T, v)
Input: v in T
Output: height of v in T
h <- 0;
foreach w in T.children(v) do
h <- max { h, 1 + height(T, w) };
return h- The
foreachenumerates the children through the iterator. At the end . - Base case: at a leaf
children(v)is empty, the loop does nothing, the result is . - Height of the whole tree:
height(T, T.root()). - This is a postorder patternthe height of a node is computed only after the heights of all its childrenTree Traversals →.
Complexity. The recurrence is hard to solve (number of calls and subproblem sizes depend on the instance), so use the recursion tree for the call height(T, v):
- The algorithm is invoked exactly once for each node : the recursion tree has one node per descendant of .
- The cost of the call on , excluding recursive calls, is , where is the number of children of : initialisation and return are , the loop runs times, the covers the leaf case.
- By Proposition 8.4, , so the cost is .
height on visits all nodes of .
Proposition 8.4
In a tree with nodes, , where is the number of children of .
Proof. Every node except the root has a unique parent, so it contributes exactly 1 to the sum (as a child of its parent). Counted the other way round: each node except the root is counted exactly once, as the child of its parent. The root is nobody's child. Hence the sum is .
Example with : .
Depth versus height: an asymmetry
| depth of | height of | |
|---|---|---|
| measures | distance from the root | distance from the farthest leaf |
| computation | one path upward | explores the whole subtree |
| cost |
can be much larger than if the tree is wide. Depth is cheap, height can be much more costly.
Related: Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals → (visiting all nodes, computing depths of all nodes in ), Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →.
Versione ripasso
Rooted tree: a root ; every has exactly one parent; going up from any reaches (the third condition excludes forests where and are parents of each other).
- ancestor: or ancestor of ; descendant: the reverse. Interior: at least 1 child. Leaf (external): no children. : all descendants of . Ordered: children of each node are linearly ordered.
- Recursive: , .
- , . Level = nodes of depth .
- , ; .
- Prop. 8.3: . Proof: induction on ; base gives 0; step: , apply the hypothesis to each , and .
- Prop. 8.4: (each non-root node counted once, as a child of its parent).
depth(T, v): if T.isRoot(v) return 0 else return 1 + depth(T, T.parent(v))
height(T, v): h <- 0; foreach w in T.children(v): h <- max{h, 1 + height(T, w)}; return hdepth: (also worst case); the iterative version has the same cost.heighton : with , via Prop. 8.4.- Tree interface: only
root()gives direct access; then navigate withparentandchildren; all methods exceptchildren,iterator,positions.
Typical mistakes: forgetting the (cost on the root is not ); saying height costs (it visits the whole subtree); mixing depth (from the root) with height (from the leaves); forgetting that a node is its own ancestor.
See Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals → and Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →.