插入最中点
/*Given a sorted (increasing order) array, write an algorithm to create a binary tree with
minimal height
*/
#include <iostream>
#include <queue>
using namespace std;
class Node{
public:
int data;
Node *lchild,*rchild;
Node(int a=0, Node* l= 0, Node* r = 0):data(a),lchild(l),rchild(r){}
};
class Tree{
public:
Node* root;
Tree():root(0){}
Tree(int ar[],int l){
root = 0;
for(int i = 0; i<l; i++)
insert(ar[i]);
}
void insert(int);
bool is_empty(){ return !root;}
int height(Node*);
void preorder(Node*,int);
void destroy(Node*);
void traorder(Node*);
Node* treebuild(int[],int,int);
};
void Tree::insert(int k){
if(is_empty())
root = new Node(k);
else{
Node* temp = root;
Node* parent;
while(temp){
parent =temp;
if(temp->data > k)
temp = temp->lchild;
else temp = temp->rchild;
}
temp = new Node(k);
if(parent->data > k)
parent->lchild = temp;
else parent->rchild = temp;
}
}
void Tree::preorder(Node* r,int d)
{
if(r){
preorder(r->lchild, d+1);
cout<<r->data<<" ";
preorder(r->rchild, d+1);
}
}
int Tree::height(Node* r){
if(!r)
return 0;
else{
int hr = height(r->rchild);
int hl = height(r->lchild);
return hr > hl ? hr+1 : hl+1;
}
}
void Tree::destroy(Node* r){
if(r){
destroy(r->lchild);
destroy(r->rchild);
delete r;
}
}
//print tree level by level
void Tree::traorder(Node* r){
if(!r) return;
queue<Node*> q;
q.push(r);
Node* temp;
Node* level = 0;
while(!q.empty()){
temp = q.front();
//whenever meet the next level, change to the next line.
if(temp == level){
cout<<endl;
level = 0;
}
cout<<temp->data<<" ";
if(temp->data == 7)
int i =1;
q.pop();
//keep track of the first time when this level's children are pushed into the queue.
if (temp->lchild != NULL) {
q.push(temp->lchild);
if(!level) level = temp->lchild;
}
if (temp->rchild != NULL){
q.push(temp->rchild);
if(!level) level = temp->rchild;
}
}
cout<<endl;
}
Node* Tree::treebuild(int ar[], int b, int e){
if (b > e) return NULL;
int k = (b+e)/2;
root = new Node(ar[k],treebuild(ar,b,k-1),treebuild(ar,k+1,e));
return root;
}
int main(){
int ar[]={1,2,3,4,5,6,7,8,9,10,11,22,32};
Tree ll;
ll.treebuild(ar,0,12);
ll.traorder(ll.root);
ll.destroy(ll.root);
}