Professional Documents
Culture Documents
Name:
............................................................................................
Application Number:
Group:
...............................................................................
.............................................................................................
1
2
2
8
P
10
Exercise 1
Page 1
(2 Marks)
Draw a binary search tree by inserting the following elements in the given order: 50, 90, 30, 110, 70, 40, 10.
Solution:
o 50 OOOO
ooo
OOO
o
o
OOO
oo
o
o
OOO
wooo
'
30 ?
90 =
?
==
??
==
?
==
??
10
40
70
110
Exercise 2
Page 2
(8 Marks)
A root-to-leaf path is a sequence of nodes in a tree starting from the root node and proceeding downward to a leaf
(a node with no children). An empty tree contains no root-to-leaf paths. The cost of a path is the summation of the
values of a path. For example, the following tree has exactly four root-to-leaf paths:
}
}}
}
}}
~}
}
11 A
AA
}}
AA
}
}
AA
}
}
A
}
~
}
ll 5 PPPPP
lll
PPP
l
l
PPP
lll
l
l
PPP
ll
l
P(
l
vl
8C
}} CCCC
}
}
CC
}}
CC
~}}
!
10 A
4
AA
AA
AA
A
1
cost = 27
cost = 22
cost = 24
cost = 17
Write an internal method int maxPathCost() that returns the cost of the root-to-leaf path with the maximum
cost. Assume that the tree contains only positive integers and that the tree nodes contain data which is of type int.
Thus the implementation of the Node class is as follows:
class Node {
int data;
Node left, right;
}
For example, for the tree above, your method should return 27.
Note: Your solution MUST be implemented recursively.
Solution:
public int maxPathCost() {
return maxPathCost(root);
}
public int maxPathCost(Node node) {
if (node == null)
return 0;
return node.data + Math.max(maxPathCost(node.left), maxPathCost(node.right));
}