CareerCup-4.3
Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height
#include <iostream>
using namespace std;
typedef int Data;
struct Node
{
Node(Data d):data(d){left = right = NULL;};
Data data;
Node* left;
Node* right;
};
class Tree
{
public:
Tree():root(NULL){};
Node* root;
void build(Data data[], int from, int to, Node** node)
{
if(from > to) return;
int mid = (from + to)/2;
*node = new Node(data[mid]);
build(data, from, mid-1, &(*node)->left);
build(data, mid+1, to, &(*node)->right);
};
void inorderPrint(Node* Node)
{
if(Node == root)
cout<<"Print:"<<endl;
if(Node != NULL)
{
inorderPrint(Node->left);
cout<<Node->data<<" ";
inorderPrint(Node->right);
}
if(Node == root)
cout<<endl<<"End"<<endl;
};
};
int main()
{
Tree tree;
Data data[] = {1, 2, 3, 4, 5};
tree.build(data, 0, sizeof(data)/sizeof(Data)-1, &tree.root);
tree.inorderPrint(tree.root);
system("pause");
};