#include "Btree.cpp"
#include <bits/stdc++.h>
int Level(BTNode *bt,int h,int x) {
if(bt == NULL)
return 0;
if(bt->data == x )
return h;
else {
int lh = Level(bt -> lchild,h+1 ,x);
if(lh != 0)
return lh;
else
return Level(bt -> rchild, h+1 ,x);
}
}
int main() {
BTNode *bt;
int a[]= {5,2,3,4,1,6};
int b[]= {2,3,5,1,4,6};
int n = sizeof(a) / sizeof(a[0]);
bt = CreateBTree(a, b, n);
DispBTree(bt);
int x = 1;
cout << endl << x << " 结点的层次为:" << Level(bt,1,x);
DestroyBTree(bt);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
typedef struct BNode {
int data;
struct BNode *lchild,*rchild;
}BTNode;
BTNode *CreateBTree(int a[],int b[], int n) {
int k;
if(n <= 0)
return NULL;
BTNode *bt =(BTNode *) malloc (sizeof(BTNode));
bt -> data = a[0];
for(k = 0; k < n; k++)
if(a[0] == b[k])
break;
bt -> lchild = CreateBTree(a+1, b, k);
bt -> rchild = CreateBTree(a+k+1, b+k+1,n-1-k);
return bt;
}
void DispBTree(BTNode *bt){
if (bt != NULL){
cout << bt->data << " ";
DispBTree(bt->lchild);
DispBTree(bt->rchild);
}
}
void DestroyBTree(BTNode *bt){
if(bt == NULL) {
return ;
}else{
DestroyBTree(bt -> lchild);
DestroyBTree(bt -> rchild);
free(bt);
}
}