Chapter 6. Trees I

6.1 The Tree Abstract Data Type

A tree is an ADT that stores elements hierarchically. With the exception of the top (root) element, each element in a tree has a parent element and zero or more children.
6.1.1 Terminology and Basic Properties
  • Root: node without parent (A)
  • Internal node: node with at least one child (A, B, C, F)
  • External node (a.k.a. leaf ): node without children (E, I, J, K, G, H, D)
  • Ancestors of a node (K): parent (F), grandparent (B), grand-grandparent (A), etc.
  • Depth of a node (F): number of ancestors (2)
  • Height of a tree: maximum depth (3) of any node (J)
  • Descendant of a node (A): child (B), grandchild (F), grand-grandchild (I), etc.
  • Subtree, rooted at a node (C) consists of the node (C) and all its descendents (G, H)

Ordered Trees

6.1.2 Tree ADT Functions
6.1.3 A Tree Interface
html-6.1a (InspectablePositionalContainer)
html-6.1b (PositionalContainer)
html-6.1c (InspectableTree)
html-6.1d (Tree)


6.2 Basic Algorithms on Trees

6.2.1 Running-Time Assumptions


Input
Output

root() None
Position
O(1)
parent(v) Position Position O(1)
isInternal(v)
Position bool
O(1)
isExternal(v) Position bool
O(1)
isRoot(v) Position bool
O(1)
children(v) Position Iterator of positions O(cv)
swapElements(v,w) Two positions
Nine
O(1)
replaceElement(v,e)
A position and an object
None
O(1)
elements() None
Iterator of objects
O(n)
positions() None
Iterator of positions
O(n)

6.2.2 Depth and Height

The depth of
a node v is the number of ancestors of v, excluding v itself.
html-6.3 (depth)

The height of a node v in a tree T is also defined recursively.
The height of a tree T is the height of the root of T.
html-6.5 (height1)
html-6.6 (height2)

6.2.3 Preorder Traversal
Algorithm preOrder(v)
      visit(v)
     for each child w of v
          preOrder(w)

Tree Printing: An Application of Preorder Traversal
html-6.9 (preorderPrint)

Using Preorder Traversal for Representing a Tree
html-6.10 (parentPrint)

6.2.4 Postorder Traversal
Algorithm postOrder(v)
     for each child w of v
          postOrder(w)
     visit(v)

An Illustrative Use of the Postorder Traversal
html-6.12 (postorderPrint)

A Postorder Algorithm for Computing Disk Usage
html-6.13 (diskSpace)

Other Kinds of Traversals