Example - A Binary Search Tree (BST)
You are given a minimal implementation of Binary Search Trees (insertion only). BST.java, BST.c
Add following operations:
Implementation exercises (the algorithms are discussed in the lecture notes):
Design exercises: design and implement efficient algorithms for following operations:
The BST in the example figure is not perfectly balanced.
Example: For the BST in the example figure, SearchClosest(16) returns 15.
Example: For the BST in the example figure, CheckExistTwoNodesWithSum(12) returns true.
Example: For the BST in the example figure, PrintPathFromTo(10, 18) prints 10, 15, 20, 18.
Example: For the BST in the example figure, PrintPathsWithSum(22) prints following paths: 8, 2, 5, 4, 3 and 8, 2, 5, 7.
Example: For the BST in the example figure, PrintLevels produces the sequence: 8, 2, 15, 1, 5, 10, 20, 4, 7, 18, 22, 3
Example: IsPostorderArray({1, 5, 2, 15, 8}) returns true. IsPostOrderArray({1, 15, 2, 5, 8}) returns false.
Hint: If the array represents the postorder traversal of a BST, the last element of the array corresponds with the root of the BST, and there is a first part of the array (a subarray from start until an index idx) that contains values from the left subtree and a second part of the array (from index idx+1 up to the last-1) that contains elements from the right subtree. The value of the index idx is unknown and has to be found. We know that in a BST all values in the left subtree are smaller than the root and all values in the right subtree are bigger than the root, for all nodes. If such an index idx exists, then every one of the 2 subarrays have to recursively fulfill the same condition. If no such index idx can be found, or one of the subarrays does not fulfull the condition, the sequence does not represent the postorder traversal of a BST. Finding the index idx in an array of length n can be done in O(log n) time !
Similar with the previous exercise, the tree is recursively built while ckecking the conditions.
Thinking questions