Beruflich Dokumente
Kultur Dokumente
root
A
Child (of root)
M
L N
C O
R D
P U T E
1
Definitions
Tree - a connected undirected graph with no cycles, where one of the vertices is
chosen to be the root. When we choose a root we impose an orientation of the edges
from the root to the adjacent vertices, and then from these vertices to their adjacent
vertices, etc,
Node, vertex - can have a name and carry other associated information
Root - starting point (top) of the tree
Parent (ancestor) of a node A - the node above node A
Child (descendent) of a node A - the node below node A
Siblings - nodes that have same parent
Leaves (terminal nodes) nodes with no children
Level of a node - then number of edges between this node and the root
Path from node ni to nm: a sequence of nodes ni1, ni2, nm such that n k is the parent
of n k+1
Depth of a node - the length of the path from the root to that node
Depth of the root: 0
Height of a node - the length of the longest path from that node to a leaf
Height of any leaf: 0
Height of a tree the length of the longest path from the root to a leaf (same as
height of the root)
Binary tree each node has at most two children
Perfect binary tree each node except the leaves has exactly two children and all
leaves have same depth
Properties:
2
Examples of various trees
A binary tree:
P T
O E
C L
M
R N
A D
Expression tree: A binary tree, the leaves contain the operands of the expression, and the
other nodes contain the operators.
+ +
a *
d e
b c
(a + b*c) * ( d + e)
3
A game tree:
A parse tree:
4
Computing the height of a perfect binary tree with N nodes
Level/ depth 0
Level/ depth 1
Level/ depth 2
Level/ depth 3
There are three levels, and the total number of nodes is:
1 + 2 + 22 + 23 = 24 - 1 = 15
In general, if we have a tree with M levels, the number of the nodes would be:
1 + 2 + 22 + . 2M = 2(M+1) - 1 = 2*2M - 1
We will find now how M (the height of the tree) depends on the number of the nodes.
N = 2*2M - 1
2*2M = N + 1
2M = (N+1)/2
M = log((N+1)/2)
when the tree is a list - all nodes except the leaf have only one child:
height : N-1
5
Binary Tree Traversals:
O T
M E
P U R
L A
Pre-order traversal:
Visit the root
Pre-order traverse left sub-tree
Pre-order traverse right sub-tree N D
The tree above in pre-order traversal reads C O M P U T E R L A N D
In-order Traversal
In-order traverse left sub-tree
Visit the root
In-order traverse right sub-tree
Post-order Traversal
Post-order traverse left sub-tree
Post-order traverse right sub-tree
Visit the root
Breadth first traversal - visit all nodes in level 0, then in level 1, etc.
Depth first traversal = Pre-order traversal for binary trees