1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
//
//custom constructor that takes an array and turns it into a binary search tree
//
TreeType::TreeType( ItemType a[], int len )
{
//sort array
bubbleSort( a, len );
//call recursive function
int left = 0;
int right = len - 1;
cout << "in constructor, setting root." << endl;
root = findMedian(a,left,right);
}
//function that finds median
TreeNode * TreeType::findMedian ( ItemType a[], int left, int right )
{
if ( left > right )
return NULL;
TreeNode *tree = new TreeNode;
int mid = (left+right)/2;
cout << "Creating a treenode" << endl;
cout << "a[mid} is: " << a[mid] << endl;
tree -> info = a[mid];
tree -> left = findMedian( a, left, mid - 1);//recursively call the left subtree
tree -> right = findMedian(a, mid + 1, right );//recursively call the right subtree
return tree;
}
//in main
case 'O':
{
cout << "Enter a string: ";
cin >> words;
TreeType optimalTree( words, strlen(words));
optimalTree.Print();
cout << endl;
break;
}
//sample run
Enter a string: YHGTRFB
len is: 7
in constructor, setting root.
left is: 0
right is: 6
Creating a treenode
a[mid} is: F
left is: 0
right is: 2
Creating a treenode
a[mid} is: F
left is: 0
right is: 0
Creating a treenode
a[mid} is: F
left is: 0
right is: -1
left is: 1
right is: 0
left is: 2
right is: 2
Creating a treenode
a[mid} is: F
left is: 2
right is: 1
left is: 3
right is: 2
left is: 4
right is: 6
Creating a treenode
a[mid} is: F
left is: 4
right is: 4
Creating a treenode
a[mid} is: F
left is: 4
right is: 3
left is: 5
right is: 4
left is: 6
right is: 6
Creating a treenode
a[mid} is: B
left is: 6
right is: 5
left is: 7
right is: 6
F
/ \
F F
/ \ / \
F F F B
|