完全二叉树的构造与遍历

#ifndef BinaryTree_H_
#define BinaryTree_H_

struct binarytree {
	struct binarytree * left;
	struct binarytree * right;
	char content;
};

int length(char * array);
struct binarytree * init(char * p , int n);
int pretravers(struct binarytree * root);
int backtravers(struct binarytree * root);
int medtravers(struct binarytree * root);
int count(struct binarytree * root);
int height(struct binarytree * root);
#endif

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "bitree.h"

int num=0;

int main(){
	char array[10];
	scanf("%s",array);
	int n=length(array);
	struct binarytree * root;
	root=init(array,n);
	printf("pretravers:\n");
	pretravers(root);
	printf("\n");
	printf("medtravers:\n");
	medtravers(root);
	printf("\n");
	printf("backtravers:\n");
	backtravers(root);
	printf("\n");

return 0;
}

struct binarytree * init(char * p , int n){
	struct binarytree * root;
	struct binarytree * ptr[n+1];
	for(int i=1;i<n+1;i++){
		ptr[i]=(struct binarytree *)malloc(sizeof(struct binarytree *));
		ptr[i]->content=*(p+i-1);
		ptr[i]->left=NULL;
		ptr[i]->right=NULL;
	}
	for(int i=1;i<n+1;i++){
		if(i/2 != 0){
			if(i%2==0){
				ptr[i/2]->left=ptr[i];
			}
			if(i%2 == 1){
				ptr[i/2]->right=ptr[i];
			}
		}
	}

	root=ptr[1];
	return root;
}

int length(char * array){
	int length=0;
	char * parray=array;
	while(*parray != '\0'){
		length++;
		parray++;
	}
	return length;
}

int pretravers(struct binarytree * root){
	if(root==NULL){
		return 0;
	}

	printf("%c-->",root->content);
	pretravers(root->left);
	pretravers(root->right);
}

int backtravers(struct binarytree * root){
	if(root==NULL){
		return 0;
	}
	backtravers(root->left);
	backtravers(root->right);
	printf("%c-->",root->content);
}

int medtravers(struct binarytree * root){
	if(root==NULL){
		return 0;
	}
	medtravers(root->left);
	printf("%c-->",root->content);
	medtravers(root->right);
}


int height(struct binarytree * root){
	int num=count(root);
	return log10(num+1)/log10(2)+1;
}

int count(struct binarytree * root){
	if(root == NULL){
		return num;
	}
	num++;
	count(root->left);
	count(root->right);
}
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值