Sie sind auf Seite 1von 9

German University in Cairo

Fa ulty of Media Engineering and Te hnology


Prof. Dr. Slim Abdennadher
Data Stru tures and Algorithms, Winter Term 2008-2009
Pra ti e Assignment 10
Dis ussion: 10.01.2009 - 15.01.2009

Exer ise 10-1

To be dis ussed in the Tutorial

Traversal

a) Given the following binary sear h tree.


75 PPP
PPP
qqq
q
PPP
q
qq
PPP
q
q
q
PP'
xqq
50 <
90 <
<<
 <<<
<<

<<

<<

<




22
60 <
98
 <<<

<<

<

55
65

Give the preorder, postorder and inorder traversals of the tree above.

Solution:
Preorder Traversal: 75, 50, 22, 60, 55, 65, 90, 98
Postorder Traversal: 22, 55, 65, 60, 50, 98, 90, 75
Inorder Traversal: 22, 50, 55, 60, 65, 75, 90, 98

b) Whi h traversal order lists the info elds of the tree nodes in sorted fashion?

Solution:
Inorder Traversal
) Given the following output of the preorder traversal of a binary sear h tree.
90, 50, 20, 5, 25, 75, 66, 80, 150, 95, 92, 111, 175, 166, 200

Constru t the binary sear h tree. Is the tree unique? Show your workout.

Solution:
The tree is unique.

d) Given a preorder traversal and an inorder traversal of a binary tree, a unique binary tree that
satises the traversals an be onstru ted. Given the following preorder and inorder traversals,
onstru t the binary tree. Trees may be drawn using text hara ters, assuming a uniformly-spa ed
font.

Preorder Traversal: a, e, f, h, g, b, , d
Inorder Traversal: h, f, e, g, a, , b, d

Solution:

Exer ise 10-2


Considering the following traversals of the same binary tree:
Inorder traversal: 2 4 9 5 8 3 1
Postorder traversal: 4 5 9 2 1 3 8
It is possible to onstru t the unique tree that these traversals represent:

8Q
nnn QQQQQ
n
n
QQQ
n
QQQ
nnn
n
n
QQQ
n
Q(
wnnn
2@
3@
@@
@@
@@
@@
@@
@@
@
@
9@
1
~~ @@@
~
@@
~
@@
~~
~~~
4
5

Constru t the trees with the following traversals:


a) Inorder traversal: 9 8 6 1 2 5 4
Postorder traversal: 9 6 1 8 5 4 2

Solution:
n 2 PPPP
PPP
nnn
n
n
PPP
nn
n
PPP
n
n
n
PP'
n
wnn
8@
4
~
~ @@
@@
~~
~~
~
~
@@
~~
~~
@
~~~
~~~
1
5
9
~
~~
~
~~
~~~
6

b) Inorder traversal: 4 5 6 7 3 2
Preorder traversal: 2 3 4 7 6 5

Solution:

mm 2
mmm
m
m
mmm
mmm
m
m
mv

~~
~~
~
~
~~ ~
4@
@@
@@
@@
@
7
~~
~~
~
~
~~~
6@
@@
@@
@@
@
5

) Preorder traversal: 1 2 3
Postorder traversal: 3 2 1

Solution:
It is not possible to onstru t one unique tree. There are several possibilities. This is the ase
be ause neither the preorder nor the postorder traversals indi ate whi h elements lie on the right
and whi h on the left. For that we need an inorder traversal.

Exer ise 10-3

To be dis ussed in the Tutorial


The height of a tree is the number of the highest level.
a) What is the smallest number of nodes a binary tree of height n an have? Show your workout.

Solution:
The smallest number of nodes a binary tree of height n an have is n - 1. Here is an example of a
binary tree of height n with n - 1 nodes.
Path length
/
O

.
/
O
/

.
.

/
O

Number of nodes length

n-1

n + 1

b) What is the largest number of nodes a binary tree of height n an have? Show your workout.

Solution:
The largest number of nodes a binary tree of height n an have is 2n+1 1. Here is the binary tree
of height n with the largest number of nodes.
O

/ \
O
O
/ \
/ \
O O O O
/ \ / \ / \ / \
.
.

.
.
/ \
O O
/ \ / \
O O O O

.
.
/ \
O O
/ \ / \
O O O O

Path length
0

Number of nodes
1

n-1
n

2^n-1
2^(n+1) - 1

Exer ise 10-4

To be dis ussed in the Tutorial


A ternary tree is a tree where ea h node an have at most 3 hildren. Consider a ternary tree of height 3.
a) What is the minimum number of nodes in a ternary tree of height 3?

Solution:
The minimum number of nodes in a ternary tree of height 3 is 4.
b) What is the maximum number of nodes in a ternary tree of height 3?

Solution:
The maximum number of nodes in a ternary tree of height 3 is 40.
In level 0: 1 node
In level 1: 3 nodes
In level 2: 3 3 = 9 nodes
In level 3: 9 3 = 27 nodes

Exer ise 10-5

To be dis ussed in the Tutorial

Height - Re ursion and Iteration

We frequently number the levels in a rooted tree, starting with 0 for the root node level and in reasing
downwards. We all the number of the highest level the height or depth of the tree. Note that a tree
onsisting of a single leaf is dened to be of height zero.
a) Write a re ursive method to al ulate the height of a binary sear h tree.

Solution:
int heightRe ()
{
return heightRe (root, -1);
}
int heightRe (Node urrent, int depth)
{
if( urrent == null) return depth;
++depth;
int leftDepth = heightRe ( urrent.left, depth);
int rightDepth = heightRe ( urrent.right, depth);
return (leftDepth>rightDepth)?leftDepth:rightDepth;
}

b) Write an iterative method to al ulate the height of a binary sear h tree.

Solution:
The iterative method of the height will be implemented using linked lists.
int height()
{
if(root == null)
return -1;
int depth = -1;
LinkedList urrentLevel = new LinkedList();
urrentLevel.addLast(root);
while(! urrentLevel.isEmpty())
{
LinkedList nextLevel = new LinkedList();

while(! urrentLevel.isEmpty())
{
Node temp = (Node) urrentLevel.removeFirst();
if(temp.left != null) nextLevel.addLast(temp.left);
if(temp.right != null) nextLevel.addLast(temp.right);
}
urrentLevel = nextLevel;
++depth;
}
return depth;

Exer ise 10-6

To be dis ussed in the Lab

Range Printing

Write a method void printRange(int lowerBound, int upperBound) that prints all keys k in a binary
tree where lowerBound k upperBound. For example:


5

q 50 MMMM
MMM
qqq
q
q
MMM
q
q
q
MM&
xqqq
20 <
75 <
<<
 <<<
<<

<<
<<

<


25
66
80

invoking printRange(20, 90) on the binary tree above should print: 20 25 50 66 75 80

Solution:
publi void printR(int lower, int upper)
{
return printRange(root, lower, upper);
}
print void printRange(Node p,int lower, int upper)
{
if(p != null)
{
if(p.data >= lower && p.data <= upper)
{
System.out.println(p.data);
printRange(p.left, lower, upper);
printRange(p.right, lower, upper);
}
else if(p.data < lower)
printRange(p.right, lower, upper);
else
printRange(p.left, lower, upper);
}
}

Exer ise 10-7

To be dis ussed in the Lab

Level Printing

Implement a method that prints all the nodes in a ertain level For example:
6

ss
ss
ss
s
ysss
95:
 :::
::


:

92
111

150 J
JJ
JJ
JJ
JJ
%
175
 888

88

88




166
200

invoking printLevel(2) on the binary tree above should print: 92 111 166 200 Hint: you an pass
another parameter to the method.

Solution:
publi void printLevelH(int l)
{
printLevel(root,l,0);
}
void printlevel(Node p ,int level ,int x)
{
if(p == null) System.out.print("
");
else if(x==level) System.out.println(p.key);
else
{
printlevel(p.left,level+1,x);
printlevel(p.right,level+1,x);
}
}

Exer ise 10-8

To be dis ussed in the Lab

Breadth First traversal

Write the method breadthTraversal that will print all the nodes in the tree level by level For example:
nn 9 NNNN
NNN
nnn
n
n
NNN
nn
n
n
NNN
n
'
wnnn
5@
14
@
~
 <<<
@@
~

~
<<

@@
~
<<

@@
~~

~


~~
4
8
12
16

invoking breadthTraversal() on the binary tree above should print: 9 5 14 4 8 12 16

Solution:
publi void printBreadth()
{
int height = heightRe (root,-1);
int = 0;
while( <= height)
{
printLevelH( );
System.out.println();
++;
}
}

Exer ise 10-9


Write a re ursive method that will nd the sum of all the nodes in the tree. Your method should have a
parameter of type TreeNode, and it should return a value of type int.

Solution:
stati int treeSum( Node root ) {
// Find the sum of all the nodes in the
// tree to whi h root points.
if ( root == null ) {
// The sum of the nodes in an empty tree is zero.
return 0;
else {
// Add the item in the root to the sum of the
// items in the left subtree and the sum of the
// items in the right subtree.
int total = root.item;
total += treeSum( root.left );
total += treeSum( root.right );
return total;
}
}

Exer ise 10-10

Prex Notation

In prex notation the operator is written before its operands. Write a Java program that reads an
arithmeti expression written in prex notation and represents it in a binary tree format. Sti k for the
moment to expressions made up of numbers and the operators +, -, *, and /. For example,
-*+ab +de

would be represented as:

Solution:
lass PrefixParser
{
String expr;
Node parse(String in)
{
expr = in;

return parse();
}
Node parse()
{
Node root = new Node(expr. harAt(0));
expr = expr.substring(1);
if(Chara ter.isLetter(expr. harAt(0)))
{
root.left = new Node(expr. harAt(0));
expr = expr.substring(1);
}
else
root.left = parse();
if(Chara ter.isLetter(expr. harAt(0)))
{
root.right = new Node(expr. harAt(0));
expr = expr.substring(1);
}
else
root.right = parse();
return root;
}
publi stati void main(String args[)
{
PrefixParser p = new PrefixParser();
Node treeRoot = p.parse("-*+ab +de");
System.out.println(traverseInfix(treeRoot));
}
stati String traverseInfix(Node urrent)
{
if( urrent == null)
return "";
else if( urrent.left == null && urrent.right == null)
return "" + urrent.data;
else
return ( "(" + traverseInfix( urrent.left) + urrent.data
+ traverseInfix( urrent.right)) + ")";
}
}
lass Node
{
har data;
Node left;
Node right;
publi Node( har data)
{
this.data = data;
}
}

Das könnte Ihnen auch gefallen