Created
July 19, 2014 14:15
-
-
Save xun-gong/bcc74b741c02535a5d1e to your computer and use it in GitHub Desktop.
CareerCup4.3.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Chapter 4 | |
* 4.3 Given a sorted (increasing order) array with unique integer elements, | |
* write an algorithm to create a binary search tree with minimal height. | |
*/ | |
/* Recursive way to solve this problem */ | |
#include <iostream> | |
using namespace std; | |
// Define tree_node struct | |
typedef struct tree_node { | |
int value; | |
struct tree_node* left; | |
struct tree_node* right; | |
tree_node(int value); | |
} tree_node; | |
// Constructor | |
tree_node::tree_node(int value) { | |
this->value = value; | |
left = NULL; | |
right = NULL; | |
} | |
// Sorted array to BST | |
tree_node* buildBST(int a[], int start, int end) | |
{ | |
if (start > end) // if start == end, means the first and last element is processing | |
return NULL; // Base case | |
int mid = (end + start) / 2; // Watch out: not (end - start) / 2 | |
tree_node* root = new tree_node(a[mid]); // middle element must be root to ensure miminum height | |
root->left = buildBST(a, start, mid - 1); // recurse left part | |
root->right = buildBST(a, mid + 1, end); //recurse right part | |
return root; | |
} | |
// Preorder print out BST | |
void preOrder(tree_node* root) | |
{ | |
if (root == NULL) | |
return; | |
cout << root->value << " "; | |
preOrder(root->left); | |
preOrder(root->right); | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int a[5] = {1, 2, 3, 4, 5}; | |
tree_node* BST = buildBST(a, 0, 4); | |
preOrder(BST); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment