Vous êtes sur la page 1sur 1

Christopher

Pina Norman
CST370 Final Exam Project 2
February 24, 2017

a) Design and Pseudocode

Lowest common ancestor can be found when the two given values diverge in a BST. This means that the
lowest common ancestor is the node at which one of the values is bigger than the current nodes value and
the other is smaller, or one of the values is equal to the current value and the other is bigger or smaller.

//Implementation of lowest common ancestor: Method takes two items and finds their lowest common ancestor in a binary
search tree. Method assumes that the items exist in the binary search tree. Returns NULL if BST is empty.
commonAncestor (item1, item2)
{
Declare current pointer and set equal to root //Done to keep myRoot intact
IF current = NULL return NULL //Return null if BST is empty
WHILE current pointer is not null //To avoid weird results from empty tree
IF item1 < current.data AND item2 < current.data //If both items are less than current value, lowest
current = current.left //common ancestor must be in left subtree
ELSE IF item2 > current.data AND item2 > current.data //If both items are greater than current value, lowest
current = current.right //common ancestor must be in right subtree
ELSE
end while loop //If previous conditions are not met then one of the two
} //given values has diverged from the other, which makes the
//current node the lowest common ancestor.

b) Implementation and Testing

The test below shows that the program is able to find the appropriate lowest common ancestor for each of
the pair values given. The test is based on the binary search tree provided in the prompt.



c) Running Time

The run time for this algorithm is O(h), where h is the height of the binary search tree. If the tree is balanced
this algorithm could have a running time of O(log(n)) since we are eliminating nearly n/2 nodes after each
iteration. At worst if the binary search tree is completely unbalanced the running time would be O(n).

d) Video Overview: https://youtu.be/N1EVozrK_zg

Vous aimerez peut-être aussi