Professional Documents
Culture Documents
Cairo University
Faculty of Engineering
Computer Engineering Department
Data Structures and Algorithms
Sheet #7
Trees Commented [E1]:
[Sheet Structure]:
Some differences in trees terminology and which terminology you must Part I: Exercises (simple questions without code):
use in any exam in the course: A – General Trees
B – Binary Trees
C – Binary Search Trees (BST)
D – Heap
As instructed by the doctor, in the reference we use: Part II: Problems (code)
- The node “Levels”, starts with 1 (NOT: 0). A – Binary Trees
B – Binary Search Trees
- The binary tree that has its maximum number of nodes in each level is called:
“Full” Tree (Not: complete).
- The binary tree that has minimum height (all the levels except last contain max
num of nodes) and the nodes in the last level are consecutive (no gaps) is
called: “Complete” Tree (Not: nearly complete).
- In BST, if you want to insert a node that already existing, Do NOT make another node
for it in the tree. Instead, increment the count of this node (the count is a data
member NOT the node’s value).
Part I: Exercises
A. General Trees
Solution
[1] Tree nodes {A, B, F, C, G, D, E, H, I, J, K, L}
[2] Tree Branches {AB, AF, BC, CD, CE, FG, GH, GI, GJ, IK, KL}
[3] Root Nodes that don’t have parent = {A}
[4] Leaves Nodes that don’t have children {D, E, H, L, J}
[5] Internal nodes = all nodes – root – leaves
= {B, F, C, G, I, K}
[6] Parents Nodes that have children
= all nodes – leaves
= {A, B, F, C, G, I, K}
(a) (b)
2. Binary Trees
Full: has its max number of nodes in each level …. The last
level is full
Complete: has minimum height (all the levels except last
contain its max num of nodes) and the nodes in the last
level are consecutive (no gaps) i.e. the left of the first parent
is inserted then the right of it then the left of the second parent
and so on.
(a) (b) (c)
As instructed by the doctor, our reference use the “Full”
and the “Complete” terminology as described above. You
MUST use this terminology in any exam in the course.
Some other references call the “Full” tree Complete and the
“Complete” tree Nearly Complete but we will NOT use
this terminology in the course.
Commented [E7]:
[ Question 3 (b) : The balance factor ]
(h) (i)
(g)
No. a:
GDH B IE A C JF K ML
No. b:
DCE B A F H G I J K
Commented [E11]:
Depth-First – [ Post-Order ]:
No. a:
GHD IE B J M L K F C A
No. b:
DEC B H K J I G F A
Note:
As instructed by the doctor, if you want to insert a node
that already existing in the BST, Do NOT make another
node for it in the tree. Instead, increment the count of this
node (the count is a data member in node NOT its value).
Commented [E17]:
Remember the note of inserting duplicates mentioned in the
previous comment.
(a) (b)
a. Search for the value 56 (show the compared nodes in order) Commented [E19]: Tree a:
b. Get the smallest value 25 40 54 -> not found
Tree b:
c. Get the largest value 70 60 50 55 -> not found
d. Insert 44, 66, and 77 into the binary search tree
Commented [E20]: Left-most = 45
Commented [E21]: Right-most = 90
Commented [M. Ismail22]:
Created by
http://visualgo.net/bst.html
f. Delete the node containing 85 from the binary search tree Commented [M. Ismail23]:
Simpler than first case
1-Find node to be delete (85)
2- As 85 has no left, then make its pointer points to its right
4. Heap This will make 80 pointer to 90 at its right
1. Define AVL trees and Heap trees. Draw an example for each.
2. Show which of the following figures are heaps and which are not. Commented [M. Ismail24]:
Heap should be
1- Full or complete BT
2- Parent ≥ both subtrees
3. Make a heap out of the following data read from the keyboard: Commented [M. Ismail25]:
Steps in general
1-Insert at 1st available leaf
Insertion here does not follow BST algo. Students usually
confuse this part with insert in BST
2-Reheap up
Answer:
4. Apply the re-heap up algorithm to the non-heap structure shown in following figure.
Answer:
The node 45 will be exchanged with 13, then with 23, then with 44
Final heap will be:
5. Apply the re-heap down algorithm to the partial heap structure shown in the following figure.
Answer:
Node 15 will be exchanged with the larger of its children exchange 15,32 then exchange 15,25
Final Heap:
Answer:
a.
40 23 32 13 11 25 21 8 10
b. Delete operation,
i. Deletes root node delete 40
iii. Reheaps down (as in problem 5 above) exchange 10 with 32 then with 25
Final heap
c. Insert 38
Inserts 38 at 1st available leaf (right child of node 13)
Then reheaps up: exchange 38 and 13, then 38 and 23, then 38 and 32
Final Heap:
1. Write a member function that counts the number of nodes in a binary tree. class Node
{
int data;
Node* left;
// Private (Utility) Node* right;
// Recursive function public:
// to be used inside the public CountN() function ...
int BinTree::RecCount (BinaryNode * subRoot) const };
{ class BinTree
if ( ! subRoot) return 0; {
return 1 + RecCount (subRoot -> getleft()) + RecCount (subRoot -> getright()); Node * root;
} public:
};
// Public Function
int BinTree::CountN ()
{
return RecCount(root);
}
2. Write a member function that returns the sum of all the nodes in a binary tree.
// Private (Utility)
// Recursive function
// to be used inside the public function
int BinTree::RecSum (BinaryNode * subRoot) const
{
if( ! subRoot ) return 0;
return subRoot -> getdata() + RecSum (subRoot -> getleft()) + RecSum (subRoot -> getright());
}
// Public Function
int BinTree::Sum ()
{
return RecSum (root);
}
3. Write a member function that counts the number of leaves in a binary tree.
// Public Function
Same way as shown in previous questions.
4. Write a member function that counts the number of leaves that contain even values in a binary tree.
// Public Function
Same way as shown in previous questions.
5. Write a member function that returns the maximum value of all the nodes in a binary tree. Assume
all values are non-negative; return -1 if the tree is empty.
// Public Function
Same way as shown in previous questions.
6. Write a member function that prints all the keys that are less than a given value, V, in a binary tree.
// Public Function
Same way as shown in previous questions.
7. Write a member function that returns true if the sum of all the nodes in a binary tree equal to a given
value, V.
8. Write a member function is_mirror that returns true if the two passed tree are mirrors; every left
child in the first tree is a right second tree and vice versa.
9. Write a member function that creates a mirror image of a binary tree. All left children become right
children and vice versa. The input tree must remain the same.
// Public Function
Same way as shown in previous questions.
10. Write a member function double_tree that, for each node in a binary tree, it creates a new duplicate
node and insert it as the left child.
So the tree...
5
/ \
1 3
Is changed to...
5
/ \
5 3
/ /
1 3
/
1
// Public Function
Same way as shown in previous questions.
11. Write a member function to delete all the leaves from a binary tree, leaving the root and intermediate
nodes in place. (Hint: Use a preorder traversal.)
12. Write a member function same_structure that returns true if the two passed tree are structurally the In a simpler way, you can think of it as follows.
same whatever the data inside them.
In this function the “subRoot” parameter is sent by reference
because it may be changed inside the function (be equal to
NULL if leaf).
// Private (Utility) Recursive function
So when we send “ subRoot -> getleft(); ” in the recursive
bool BinTree::RecIsSameStructure (BinaryNode * rootA, BinaryNode * rootB) const
function call, that may change the root of the left subtree to
{ NULL if leaf, so we must use setleft() on subRoot (the setter
if ( ! rootA && ! rootB) return true; of its left) to change its left to be the new root of the left
if ( rootA && ! rootB || rootB && ! rootA) return false; subtree (NULL).
return RecIsSameStructure (rootA -> getleft() , rootB -> getleft() ) &&
That’s why we used a temp variable for left, “left”, and send it
RecIsSameStructure (rootA -> getright() , rootB -> getright() ); in the function call. Then, we called subRoot -> setleft( left );
} to set the left of the subRoot with the “left” after change.
// Public Function
Same way as shown in previous questions.
14. Given a binary tree, write a member function that prints out all of its root-to-leaf paths, one per line.
Not so easy !
Idea:
▪ Each time you visit a node, add it to the path to be printed (shared variable "pass by ref")
▪ Once you reached a leaf, print flush the stored path (root-to-leaf) on the screen
▪ Remove only the leaf from the printed path as the remaining of the path may be needed to
print another branch
▪ For non-leaf nodes, Print all left paths, then print all right paths, then remove this node from
the path to print as all paths passing through it have been printed
The recursive function takes more parameters and print the paths (parameters: subRoot, integer array,
last item index).
if( ! subRoot -> getleft() && ! subRoot -> getright() ) //This is a leaf ==> path finished , print it
{
for(int i=0; i<=lastitem; i++)
cout<<path[i]<<" ";
cout<<endl;
lastitem --; // decrement lastitem to remove this leaf from the path
return;
}
if(subRoot -> getleft()) RecPrintPaths ( subRoot -> getleft() , path , lastitem);
if(subRoot -> getright()) RecPrintPaths ( subRoot -> getright() , path , lastitem);
lastitem --; //remove this node as all paths from it have been printed
}
15. The height of a tree is the maximum number of nodes on a path from the root to a leaf node. Write a
member function that returns the height of a binary tree.
// Public Function
Same way as shown in previous questions.
16. A balanced binary tree is a tree in which all the following conditions are satisfied:
a. the left and right sub-trees heights differ by at most one level
b. the left sub-tree is balanced
c. the right sub-tree is balanced
Write a member function that checks if a given tree is balanced or not.
// Public Function
bool BinTree::IsBalanced ()
{ RecIsBalanced (root); }
17. A full binary tree is a tree in which every node other than the leaves has two children.
Write a member function that checks whether a given tree is full or not.
18. Write a member function that determines whether a binary tree is complete.
19. Rewrite the binary tree pre-order, in-order and post-order traversal member functions using a
stack instead of recursion.
3. Write a member function that returns the minimum data value found in BST tree.
4. Write a member function that returns number of nodes less than a specific value in BST tree
// Public Function
Same way as shown in previous questions.
5. Write a member function that returns a sub-tree that has nodes sum equal to an input value.