For example:
Assignment3_E1_16_1234_Slim_Abdennadher.java
Exercise 3-1
(10 Marks)
downwards to a leaf (a node with no children). For example, the following tree has exactly four root-toleaf paths:
mm 5 OOOO
OOO
mmm
m
m
OOO
mm
m
m
OOO
mm
m
O'
m
mv
13 >
>>
>>
>>
11 >
>>
>>
>>
8@
@@
@@
@@
@
4
The root-to-leaf paths from the left-most path to the right-most path are:
5 4 11 7
5 4 11 2
5 8 13 1
584
In this problem you are required to traverse the binary tree, and reverse the data values contained along
each path, starting from the left most path. Thus after the rst reservse traversal, the path:
{5 4 11 7 } is reversed to {7 11 4 5} leading to this tree:
11
4>
>>
~
~
>>
~~
>>
~
~
>
~
~
~
nn 7 OOOOO
nnn
OOO
n
n
OOO
nn
n
n
n
OOO
nv nn
'
13 >
>>
>>
>>
2
8@
@@
@@
@@
@
4
The path-reversal is repeated for all paths till the right-most path, the nal tree should look like:
5
m 4 OOOO
mmm
OOO
m
m
OOO
mmm
m
OOO
m
mm
m
O'
m
mv
11 >
>>
>>
>>
13 >
>>
>>
>>
8>
>>
>>
>>
>
7
Hint: You might nd it useful to have the recursive helper method pass a linked list or array of the
nodes visited, and when you reach a leaf node, you just reverse the data values contained in the nodes.
For tracing your code, use the displayTree method below:
public void displayTree()
{
java.util.Stack<Node> globalStack = new java.util.Stack<Node>();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
"......................................................");
while(isRowEmpty==false)
{
java.util.Stack<Node> localStack = new java.util.Stack<Node>();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
{
Node temp = globalStack.pop();
if(temp != null)
{
System.out.print(temp.data);
localStack.push(temp.left);
localStack.push(temp.right);
if(temp.left != null ||
temp.right != null)
isRowEmpty = false;
}
else
{
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
"......................................................");
}
Solution:
Using the Linked Lists oered by Java:
public void reverse()
{
reverse(root,new java.util.LinkedList<Node>());
}
public void reverse(Node n, java.util.LinkedList<Node> path)
{
if (n==null)
return;
if (n.left==null&&n.right==null)
{
path.add(n);
reverseData(path);
}
else
{
path.add(n);
int oldSize = path.size(); // storing path length before recursive call
reverse(n.left,path);
displayTree();
Or using a modied LinkList class, where each Link contains an Object data and Link next:
public void reverse()
{
reverse(root,new LinkList());
}