Salta al contenuto
Note per Studenti Trees - Definitions and Properties Report

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 TT is a collection of nodes that, if not empty, satisfies:

  1. there is a special node r∈Tr \in T (the root);
  2. every v∈Tv \in T, v≠rv \neq r, has exactly one parent u∈Tu \in T (vv is a child of uu);
  3. from every v≠rv \neq r, by repeatedly moving to the parent, we eventually reach rr (every node descends from the root).

The third condition is missing in the textbook. Without it, uu could be the parent of vv and vv the parent of uu: conditions 1 and 2 hold, but that is a forest of trees, not a single tree.

Terminology

term definition
ancestor xx is an ancestor of yy if x=yx = y or xx is an ancestor of the parent of yy
descendant xx is a descendant of yy if yy is an ancestor of xx
interior (internal) node node with at least 1 child
external node (leaf) node with no children
subtree rooted at vv TvT_v = the tree made of all descendants of vv
ordered tree for every internal node a linear order is defined among its children u1,…,uku_1, \dots, u_k (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     G

Recursive definition

A non-empty rooted tree can be partitioned as T={r}∪T1∪T2∪⋯∪Tk,k≥0,T = \{r\} \cup T_1 \cup T_2 \cup \dots \cup T_k, \qquad k \ge 0, where rr is the root with children u1,…,uku_1, \dots, u_k and each TiT_i is a non-empty tree with root uiu_i (that is, Ti=TuiT_i = T_{u_i}). For k=0k = 0, TT contains only rr.

Depth, level, height

Depth of a node vv in TT:

  • depthT(v)=∣ancestors(v)∣−1\text{depth}_T(v) = \lvert \text{ancestors}(v) \rvert - 1, or equivalently
  • depthT(r)=0\text{depth}_T(r) = 0, and depthT(v)=1+depthT(parent(v))\text{depth}_T(v) = 1 + \text{depth}_T(\text{parent}(v)) otherwise.

Level ii of TT: the set of nodes of depth ii, for i≥0i \ge 0.

Height of a node vv in TT (recursive):

  • heightT(v)=0\text{height}_T(v) = 0 if vv is a leaf;
  • heightT(v)=1+max⁡w child of vheightT(w)\text{height}_T(v) = 1 + \max_{w \text{ child of } v} \text{height}_T(w) otherwise.

Height of the tree: height(T)=heightT(r)\text{height}(T) = \text{height}_T(r). 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: depth(G)=3−1=2\text{depth}(G) = 3 - 1 = 2, or 1+depth(D)=1+1+depth(A)=21 + \text{depth}(D) = 1 + 1 + \text{depth}(A) = 2. height(D)=1+height(G)=1\text{height}(D) = 1 + \text{height}(G) = 1, height(A)=1+max⁡(1,0,1)=2\text{height}(A) = 1 + \max(1, 0, 1) = 2.

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 TT: height(T)=max⁡v∈T, v leafdepthT(v)\text{height}(T) = \max_{v \in T,\ v \text{ leaf}} \text{depth}_T(v). The height of a tree is the depth of its deepest leaf.

Proof by induction on the number of nodes nn of TT.

  • Base case n=1n = 1: TT is only the root rr, which is a leaf. Height =0=depthT(r)= 0 = \text{depth}_T(r). (n=0n = 0 would be the empty tree.)
  • Inductive step: assume the property for every tree with mm nodes, 1≤m≤n1 \le m \le n, and take a tree TT with n+1>1n + 1 > 1 nodes. Then TT has a root rr and k≥1k \ge 1 subtrees T1,…,TkT_1, \dots, T_k rooted at the children u1,…,uku_1, \dots, u_k of rr, each with at most nn nodes. Then:

height(T)=1+max⁡iheightT(ui)definition of height, ui children of r=1+max⁡iheight(Ti)height of ui in T is the height of the tree Ti=1+max⁡imax⁡v∈Ti, v leafdepthTi(v)inductive hypothesis on Ti=max⁡imax⁡v∈Ti, v leaf{1+depthTi(v)}property of the max=max⁡imax⁡v∈Ti, v leafdepthT(v)see below=max⁡v∈T, v leafdepthT(v)\begin{aligned} \text{height}(T) &= 1 + \max_{i} \text{height}_T(u_i) && \text{definition of height, } u_i \text{ children of } r\\ &= 1 + \max_{i} \text{height}(T_i) && \text{height of } u_i \text{ in } T \text{ is the height of the tree } T_i\\ &= 1 + \max_{i} \max_{v \in T_i,\ v \text{ leaf}} \text{depth}_{T_i}(v) && \text{inductive hypothesis on } T_i\\ &= \max_{i} \max_{v \in T_i,\ v \text{ leaf}} \{1 + \text{depth}_{T_i}(v)\} && \text{property of the max}\\ &= \max_{i} \max_{v \in T_i,\ v \text{ leaf}} \text{depth}_T(v) && \text{see below}\\ &= \max_{v \in T,\ v \text{ leaf}} \text{depth}_T(v) \end{aligned}

depthTi(v)\text{depth}_{T_i}(v) counts the ancestors of vv up to uiu_i; adding 1 adds the root, giving depthT(v)\text{depth}_T(v). The leaves of TT are exactly the leaves of the subtrees TiT_i, so the two maxima merge into a maximum over all leaves of TT. ■\blacksquare

Tree interface and linked implementation

Two Java interfaces are needed first:

java
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).
java
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 Tree extends Iterable, it provides an iterator over its elements; positions() enumerates nodes instead of the elements they store.
  • Cost assumption: all methods are Θ(1)\Theta(1), except children, iterator and positions; the children of a node can be enumerated in time proportional to their number, and retrieving the next child takes Θ(1)\Theta(1).

In the pseudocode below the tree TT 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 dv=depthT(v)d_v = \text{depth}_T(v). The recursion tree is a chain with dv+1d_v + 1 nodes (one call per ancestor of vv, including the root, the base case). Each call costs Θ(1)\Theta(1) (isRoot is Θ(1)\Theta(1), the return does a constant number of operations). Total: Θ(dv+1).\Theta(d_v + 1).

  • The +1+1 is kept to handle dv=0d_v = 0: calling it on the root still costs a constant, not Θ(0)\Theta(0). (Often written Θ(dv)\Theta(d_v), meaning max⁡(dv,1)\max(d_v, 1).)
  • For a fixed dvd_v there is no worst case: dvd_v gives exactly the number of calls. Shallow nodes are fast, deep nodes slow.
  • In terms of the tree size nn: O(dv+1)≤O(n)O(d_v + 1) \le O(n), since dv≤n−1d_v \le n - 1; and in a degenerate tree (a chain of nn nodes) with vv the last node the cost is proportional to nn. So the worst case over nodes is Θ(n)\Theta(n).
  • Choosing the instance size, local (dvd_v) or global (nn), 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 vv, adding 1 at each step. Constant work outside the loop, constant work per iteration, exactly dvd_v iterations: Θ(dv+1)\Theta(d_v + 1), or equivalently Θ(n)\Theta(n) 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

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):

  1. The algorithm is invoked exactly once for each node u∈Tvu \in T_v: the recursion tree has one node per descendant of vv.
  2. The cost of the call on uu, excluding recursive calls, is Θ(cu+1)\Theta(c_u + 1), where cuc_u is the number of children of uu: initialisation and return are Θ(1)\Theta(1), the loop runs cuc_u times, the +1+1 covers the leaf case.

cost=Θ(∑u∈Tv(cu+1))=Θ(∑u∈Tvcu+n),n=∣Tv∣.\text{cost} = \Theta\Big(\sum_{u \in T_v} (c_u + 1)\Big) = \Theta\Big(\sum_{u \in T_v} c_u + n\Big), \qquad n = \lvert T_v \rvert.

  1. By Proposition 8.4, ∑u∈Tvcu=n−1\sum_{u \in T_v} c_u = n - 1, so the cost is Θ(n−1+n)=Θ(2n−1)=Θ(n)\Theta(n - 1 + n) = \Theta(2n - 1) = \Theta(n).

height on vv visits all nn nodes of TvT_v.

Proposition 8.4

In a tree with nn nodes, ∑u∈Tcu=n−1\sum_{u \in T} c_u = n - 1, where cuc_u is the number of children of uu.

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 n−1n - 1. ■\blacksquare

Example with n=7n = 7: 2+1+0+3+0+0+0=6=n−12 + 1 + 0 + 3 + 0 + 0 + 0 = 6 = n - 1.

Depth versus height: an asymmetry

depth of vv height of vv
measures distance from the root distance from the farthest leaf
computation one path upward explores the whole subtree TvT_v
cost Θ(dv+1)\Theta(d_v + 1) Θ(∣Tv∣)\Theta(\lvert T_v \rvert)

∣Tv∣\lvert T_v \rvert can be much larger than heightT(v)\text{height}_T(v) 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 Θ(n)\Theta(n)), 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 rr; every v≠rv \neq r has exactly one parent; going up from any vv reaches rr (the third condition excludes forests where uu and vv are parents of each other).

  • ancestor: x=yx = y or ancestor of parent(y)\text{parent}(y); descendant: the reverse. Interior: at least 1 child. Leaf (external): no children. TvT_v: all descendants of vv. Ordered: children of each node are linearly ordered.
  • Recursive: T={r}∪T1∪⋯∪TkT = \{r\} \cup T_1 \cup \dots \cup T_k, k≥0k \ge 0.
  • depth(r)=0\text{depth}(r) = 0, depth(v)=1+depth(parent(v))=∣ancestors(v)∣−1\text{depth}(v) = 1 + \text{depth}(\text{parent}(v)) = \lvert\text{ancestors}(v)\rvert - 1. Level ii = nodes of depth ii.
  • height(leaf)=0\text{height}(\text{leaf}) = 0, height(v)=1+max⁡w childheight(w)\text{height}(v) = 1 + \max_{w \text{ child}} \text{height}(w); height(T)=height(r)\text{height}(T) = \text{height}(r).
  • Prop. 8.3: height(T)=max⁡v leafdepth(v)\text{height}(T) = \max_{v \text{ leaf}} \text{depth}(v). Proof: induction on nn; base n=1n = 1 gives 0; step: height(T)=1+max⁡iheight(Ti)\text{height}(T) = 1 + \max_i \text{height}(T_i), apply the hypothesis to each TiT_i, and 1+depthTi(v)=depthT(v)1 + \text{depth}_{T_i}(v) = \text{depth}_T(v).
  • Prop. 8.4: ∑ucu=n−1\sum_u c_u = n - 1 (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 h
  • depth: Θ(dv+1)\Theta(d_v + 1) (also Θ(n)\Theta(n) worst case); the iterative version has the same cost.
  • height on vv: Θ(∑u∈Tv(cu+1))=Θ(n)\Theta(\sum_{u \in T_v} (c_u + 1)) = \Theta(n) with n=∣Tv∣n = \lvert T_v \rvert, via Prop. 8.4.
  • Tree interface: only root() gives direct access; then navigate with parent and children; all methods Θ(1)\Theta(1) except children, iterator, positions.

Typical mistakes: forgetting the +1+1 (cost on the root is not Θ(0)\Theta(0)); saying height costs Θ(height)\Theta(\text{height}) (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 →.

Teoria collegata