淘先锋技术网

首页 1 2 3 4 5 6 7
#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)  // 在左子树中找到,返回其层次 l
			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);  // 由先序序列数组a和中序序列组b 构造二叉链 bt
	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);
	}
}