Minimal Height BST
/***
4.3 Given a sorted (increasing order) array, write an algorithm to create a binary search tree with minimal height.
IDEA: start from mediate.
***/
#include<iostream>
using namespace std;
struct node {
int val;
node *left;
node *right;
};
void constructBST(node* root, int *a, int begin, int end) {
int mid;
if(begin == end) {
root->val = a[begin];
root->left = nullptr;
root->right = nullptr;
return;
} else {
node *left = new node;
node *right = new node;
mid = (begin + end) / 2;
root->val = a[mid];
root->left = left;
root->right = right;
constructBST(root->left, a, begin, mid-1);
constructBST(root->right, a, mid+1, end);
}
}
// print BST in order
void printTree(node *root) {
if(root == nullptr) return;
printTree(root->left);
cout << root->val<<" -> ";
printTree(root->right);
}
void main() {
int a[] = {1, 2, 3, 4, 5, 6, 7};
int sz = sizeof(a) / sizeof(int);
node *root = new node;
node *p = root;
constructBST(p, a, 0, sz-1);
p = root;
printTree(p);
}
4.3 Given a sorted (increasing order) array, write an algorithm to create a binary search tree with minimal height.
IDEA: start from mediate.
***/
#include<iostream>
using namespace std;
struct node {
int val;
node *left;
node *right;
};
void constructBST(node* root, int *a, int begin, int end) {
int mid;
if(begin == end) {
root->val = a[begin];
root->left = nullptr;
root->right = nullptr;
return;
} else {
node *left = new node;
node *right = new node;
mid = (begin + end) / 2;
root->val = a[mid];
root->left = left;
root->right = right;
constructBST(root->left, a, begin, mid-1);
constructBST(root->right, a, mid+1, end);
}
}
// print BST in order
void printTree(node *root) {
if(root == nullptr) return;
printTree(root->left);
cout << root->val<<" -> ";
printTree(root->right);
}
void main() {
int a[] = {1, 2, 3, 4, 5, 6, 7};
int sz = sizeof(a) / sizeof(int);
node *root = new node;
node *p = root;
constructBST(p, a, 0, sz-1);
p = root;
printTree(p);
}
Comments
Post a Comment