CS136, Lecture 20

  1. Trees
    1. Tree definition and terminology:

Trees

Trees come up naturally in many situations.

In a linear structure, every element has unique successor.

In trees, may have many.

Tree definition and terminology:

DEFINITION: A tree is either empty or consists of a node, called the root node, together with a collection of trees, called its subtrees. These trees are disjoint from each other and the root.

An edge connects a node to its subtrees.

The roots of the subtrees of a node are said to be the successors or descendants of the node.

There may be many nodes without any successors: These are called leaves. The others are called interior nodes.

All nodes except root have unique predecessor.

A collection of trees is called a forest.

Examples

A) binary search (or sort) tree

K, C, A, N, B, V, F, U, D, H, M

B) Expression trees

[A*(B-C)]+(D/~E)

Family tree terminology:

parent, child, sibling, ancestor, descendant

Node plus all of its descendents is called a subtree.

Simple path is series of distinct nodes such that there is an edge between successive nodes.

path length = number of nodes on path - 1 = # edges traversed in path,

height of node = length of longest path from that node to a leaf.
Height of tree = height of its root.

Depth of node is length of path from root to that node.

Degree of node is number of its direct descendents.

Level defined recursively:

Root is at level 0.

Level of any other node is one greater than level of its parent.

Level of a node also = length of path from root to that node.

We'll stick to binary trees for now! (All nodes of degree <= 2.)

Deal with oriented trees: Identify each subtree as being either left or right.

Lemma: If T is a binary tree, then at level k, T has <= 2k nodes.

Theorem: If T has height h then n = # nodes in T <= 2h+1 -1. Equivalently, if T has n nodes, then n - 1 >= h >= log(n+1) - 1.

Note that these bounds are tight.

A full binary tree of height h has all leaves on level h.

A complete binary tree of height h is obtained from a full binary tree of height h with 0 or more (but not all) of of the rightmost leaves at level h removed.

Say T is balanced if it has the minimum possible height for its # of nodes.

In this case, height = ceiling of log2(n+1) - 1 or O ( log2 n )

Note that a balanced tree may have lots of holes in it.