You are on page 1of 4

COMP201 SI Worksheet 8

Question One
1. If one set of elements are entered into a binary search tree but in two different orders, the BST
will be identical?

False. The trees will be different.

2. The time complexity for adding an element is the same as that for a heap, i.e., O(log(n))?

False. O(n)

3. The following BST has been visited in preorder? Visiting Order: 21, 64, 44, 90, 120, 102, 82

True
False. Postorder
False. Postorder
Question Two

1. Given the BST above, work out the preorder, postorder and inorder traversal.

Preorder: 85, 36, 21 30, 77, 82, 110, 90, 120, 111

Postorder: 30, 21, 82, 77, 36, 90, 111, 120, 110, 85

Inorder: 21, 30, 36, 77, 82, 85, 90, 110, 111, 120

2. Given the BST above, if we add a number bigger than the root element, what will be the effect?
Draw the updated BST.

Suppose we choose to add 95. Its correct position is on the right of the node with 90.
Question Three
Write pseudocode or Java code to recursively search for an element in a BST. The tree node look as
follows:

public class TreeNode<E>{

E value;
TreeNode<E> left;
TreeNode<E> right;

public TreeNode(E e){


this.value = e;
}

/** Returns true if the element is in the tree */


public boolean search(E e) {
return search(root, e);
}

public boolean search(TreeNode<E> root, E e) {


if (root == null)
return false;
else if (e.compareTo(root.element) < 0)
return search(root.left, e);
else if (e.compareTo(root.element) > 0)
return search(root.right, e);
else
return true;
}

You might also like