Sei sulla pagina 1di 35

Trees and

Binary Trees

Become Rich

Force Others Rob Stock


to be Poor Banks Fraud
The class notes are a compilation and edition from many sources. The instructor
does not claim intellectual property or ownership of the lecture notes.
Nature View of a Tree

leaves

branches
root
Computer Scientist’s View

root

leaves

branches
nodes
What is a Tree
A tree is a finite nonempty
set of elements.
It is an abstract model of a
hierarchical structure. Computers”R”Us
consists of nodes with a
parent-child relation.
Applications: Sales Manufacturing R&D
Organization charts
File systems
Programming
environments US International Laptops Desktops

Europe Asia Canada


Tree Terminology

Root: node without parent (A) Subtree: tree consisting of a


Siblings: nodes share the same parent node and its descendants
Internal node: node with at least one
child (A, B, C, F)
External node (leaf ): node without
children (E, I, J, K, G, H, D) A
Ancestors of a node: parent,
grandparent, grand-grandparent, etc.
Descendant of a node: child,
grandchild, grand-grandchild, etc. B C D
Depth of a node: number of ancestors
Height of a tree: maximum depth of
any node (3)
Degree of a node: the number of its E F G H
children
Degree of a tree: the maximum number
of its node.
I J K
subtree
Tree Properties
Property Value
A
Number of nodes
Height
B C
Root Node
Leaves
D E F Interior nodes
Ancestors of H
Descendants of B
G Siblings of E
Right subtree of A
H I Degree of this tree
Tree ADT

We use positions to abstract Query methods:


nodes boolean isInternal(p)
Generic methods: boolean isExternal(p)
integer size() boolean isRoot(p)
boolean isEmpty() Update methods:
objectIterator elements() swapElements(p, q)
positionIterator positions() object replaceElement(p, o)
Accessor methods: Additional update methods may
position root() be defined by data structures
position parent(p) implementing the Tree ADT
positionIterator children(p)
Intuitive Representation of Tree Node

List Representation
( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
The root comes first, followed by a list of links to sub-trees

How many link fields are needed in


such a representation?

Data Link 1 Link 2 … Link n


Trees

Every tree node:


object – useful information
children – pointers to its children

Data

Data   Data  Data  

Data   Data   Data  


A Tree Representation

A node is represented by
an object storing 
Element
Parent node B
Sequence of children
nodes  

A D F
B

A D F
 
C E
C E
Left Child, Right Sibling Representation

Data
Left Right
Child Sibling A

B C D

E F G H I

J K L
Tree Traversal

Two main methods:


Preorder
Postorder
Recursive definition

Preorder:
visit the root
traverse in preorder the children (subtrees)

Postorder
traverse in postorder the children (subtrees)
visit the root
Preorder Traversal

A traversal visits the nodes of a tree Algorithm preOrder(v)


in a systematic manner
visit(v)
In a preorder traversal, a node is
for each child w of v
visited before its descendants
preorder (w)
Application: print a structured
document

1
Become Rich

2 5 9
1. Motivations 2. Methods 3. Success Stories

3 4 6 7 8
1.1 Enjoy 1.2 Help 2.1 Get a 2.2 Start a 2.3 Acquired
Life Poor Friends CS PhD Web Site by Google
Postorder Traversal

In a postorder traversal, a node is Algorithm postOrder(v)


visited after its descendants
for each child w of v
Application: compute space used
postOrder (w)
by files in a directory and its
subdirectories visit(v)

9
cs16/

8
3 7
todo.txt
homeworks/ programs/
1K

1 2 4 5 6
h1c.doc h1nc.doc DDR.java Stocks.java Robot.java
3K 2K 10K 25K 20K
Binary Tree

A binary tree is a tree with the Applications:


following properties: arithmetic expressions
Each internal node has at most two decision processes
children (degree of two)
The children of a node are an ordered searching
pair

We call the children of an internal A


node left child and right child
Alternative recursive definition: a
binary tree is either B C
a tree consisting of a single node, OR
a tree whose root has an ordered pair of
children, each of which is a binary tree
D E F G

H I
BinaryTree ADT
The BinaryTree ADT Update methods may be
extends the Tree ADT, i.e., defined by data structures
it inherits all the methods implementing the
of the Tree ADT BinaryTree ADT
Additional methods:
position leftChild(p)
position rightChild(p)
position sibling(p)
Examples of the Binary Tree
Skewed Binary Tree Complete Binary Tree

A 1 A
A

B B 2 B C

C
3 D E F G
D

4 H I
E 5
Differences Between A Tree and A Binary
Tree
The subtrees of a binary tree are ordered; those of a tree
are not ordered.

A A

B B

• Are different when viewed as binary trees.


• Are the same when viewed as trees.
Data Structure for Binary Trees
A node is represented by
an object storing 
Element
Parent node
Left child node B
Right child node

 

B A D

A D    

C E
C E
Arithmetic Expression Tree

Binary tree associated with an arithmetic expression


internal nodes: operators
external nodes: operands
Example: arithmetic expression tree for the expression (2  (a -
1) + (3  b))

 

2 - 3 b

a 1
Decision Tree

Binary tree associated with a decision process


internal nodes: questions with yes/no answer
external nodes: decisions
Example: dining decision

Want a fast meal?


Yes No

How about coffee? On expense account?


Yes No Yes No

Starbucks Spike’s Al Forno Café Paragon


Maximum Number of Nodes in a
Binary Tree

The maximum number of nodes on depth i of a


binary tree is 2i, i>=0.
The maximum nubmer of nodes in a binary tree of
height k is 2k+1-1, k>=0.

Prove by induction.
k

 2
i 0
i
 2 k +1
-1
Full Binary Tree

A full binary tree of a given height k has 2k+1–1 nodes.

Height 3 full binary tree.


Labeling Nodes In A Full Binary Tree

Label the nodes 1 through 2k+1 – 1.


Label by levels from top to bottom.
Within a level, label from left to right.

2 3

4 5 6 7

8 9 10 11 12 13 14 15
Node Number Properties

2 3

4 5 6 7

8 9 10 11 12 13 14 15

Parent of node i is node i / 2, unless i = 1.


Node 1 is the root and has no parent.
Node Number Properties
1

2 3

4 5 6 7

8 9 10 11 12 13 14 15

Left child of node i is node 2i, unless 2i > n, where n is the


number of nodes.
If 2i > n, node i has no left child.
Node Number Properties

2 3

4 5 6 7

8 9 10 11 12 13 14 15
Right child of node i is node 2i+1, unless 2i+1 > n, where
n is the number of nodes.
If 2i+1 > n, node i has no right child.
Complete Binary Trees
A labeled binary tree containing the labels 1 to n with root 1, branches
leading to nodes labeled 2 and 3, branches from these leading to 4, 5 and
6, 7, respectively, and so on.
A binary tree with n nodes and level k is complete iff its nodes
correspond to the nodes numbered from 1 to n in the full binary tree of
level k.

1 1

2 2 3
3

4 5 6 7 4 5 6 7

8 9 10 11 12 13 14 15
8 9
Complete binary tree Full binary tree of depth 3
Binary Tree Traversals
Let l, R, and r stand for moving left, visiting
the node, and moving right.

There are six possible combinations of traversal


lRr, lrR, Rlr, Rrl, rRl, rlR

Adopt convention that we traverse left before


right, only 3 traversals remain
lRr, lrR, Rlr
inorder, postorder, preorder
Inorder Traversal
In an inorder traversal a node Algorithm inOrder(v)
is visited after its left subtree
and before its right subtree if isInternal (v)
inOrder (leftChild (v))
visit(v)
if isInternal (v)
inOrder (rightChild (v))
6

2 8

1 4 7 9

3 5
Print Arithmetic Expressions
Specialization of an inorder Algorithm inOrder (v)
traversal if isInternal (v){
print operand or operator when
visiting node print(“(’’)
print “(“ before traversing left inOrder (leftChild (v))}
subtree
print “)“ after traversing right print(v.element ())
subtree if isInternal (v){
inOrder (rightChild (v))
+ print (“)’’)}

 

2 - 3 b ((2  (a - 1)) + (3  b))

a 1
Evaluate Arithmetic Expressions

recursive method returning Algorithm evalExpr(v)


the value of a subtree if isExternal (v)
when visiting an internal return v.element ()
node, combine the values of
else
the subtrees
x  evalExpr(leftChild (v))
y  evalExpr(rightChild (v))
  operator stored at v
+ return x  y

 

2 - 3 2

5 1
Creativity:
pathLength(tree) =  depth(v) v  tree
Algorithm pathLength(v, n)
Input: a tree node v and an initial value n
Output: the pathLength of the tree with root v
Usage: pl = pathLength(root, 0);

if isExternal (v)
return n
return
(pathLength(leftChild (v), n + 1) +
pathLength(rightChild (v), n + 1) + n)
Euler Tour Traversal
Generic traversal of a binary tree
Includes a special cases the preorder, postorder and inorder traversals
Walk around the tree and visit each node three times:
on the left (preorder)
from below (inorder)
on the right (postorder)

L  R 
B
2 - 3 2

5 1
Euler Tour Traversal
eulerTour(node v) {
perform action for visiting node on the left;
if v is internal then
eulerTour(v->left);
perform action for visiting node from below;
if v is internal then
eulerTour(v->right);
perform action for visiting node on the right;
}

Potrebbero piacerti anche