求二叉树中节点的最大距离

如果我们把二叉树看成一个图,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,

求一棵二叉树中相距最远的两个节点之间的距离。


#include "stdlib.h"
#include "stdio.h"

typedef struct BTNode
{
	int data;
	struct BTNode *lnode;
	struct BTNode *rnode;
}BTNode;


BTNode *CreateTree(int pre[], int in[], int l1, int r1, int l2, int r2){
	
	BTNode *s;
	
	int i;
	if(l1 > r1)
		return NULL;

	s = (BTNode *)malloc(sizeof(BTNode));
	s->lnode = s->rnode = NULL;
	for(i=l2; i<=r2; ++i){
		if(pre[l1] == in[i]){
			break;
		}
	}
	s->data = in[i];

	s->lnode = CreateTree(pre, in, l1+1, l1+i-l2, l2, i-1);
	s->rnode = CreateTree(pre, in, l1+i-l2+1, r1, i+1, r2);

	return s;
}

void PrePrint(BTNode *p){
	
	if(p != NULL){
		printf("%d ", p->data);
		
		PrePrint(p->lnode);
		PrePrint(p->rnode);
	}
}


void InPrint(BTNode *p){
	
	if(p != NULL){
		InPrint(p->lnode);
		
		printf("%d ", p->data);
		
		InPrint(p->rnode);

	}
}

void FindDepth(BTNode *p, int depth, int &maxDepth){
	
	if(p != NULL){
		++depth;
		printf("current depth = %d\n", depth);
		//if depth bigger than maxDepth;
		if(depth > maxDepth){
			maxDepth = depth;
		}

		FindDepth(p->lnode, depth, maxDepth);
		FindDepth(p->rnode, depth, maxDepth);

		--depth;
	}


}


void main(){
	
	int pre[] = {10, 5, 4, 7, 12, 8, 11, 6};
	int in[] = {4, 5, 12, 7, 10, 11, 8, 6};

	BTNode *p;
	p = CreateTree(pre, in, 0, 7, 0, 7);
	
	int depth = 0;
	int maxDepth = 0;
	
	FindDepth(p, depth, maxDepth);

	printf("maxDepth = %d\n", maxDepth);

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值