编程之美系列之二叉树1—二叉树中的距离问题

本文探讨二叉树的基础知识,包括计算二叉树的深度和寻找相距最远的两个节点之间的距离。二叉树的最大距离可能是根节点的左右子树距离之和,或者单侧子树的最大距离。定义距离为节点数。
摘要由CSDN通过智能技术生成

先来点基础的,更多扩展,请猛击:http://blog.csdn.net/kay_zhyu/article/details/8868995
1、首先来个入门级的,求二叉树的深度

#include<stdio.h>
#include<string.h>
struct NODE
{
	NODE *Left;
	NODE *Right;
};
const int N = 20;
NODE node[N];
void Add(int root, int num, bool IsLeft)
{
	if(IsLeft)
	{
		if(node[root].Left != NULL)
			node[num].Left = node[root].Left;
		node[root].Left = &node[num];
	}
	else
	{
		if(node[root].Right != NULL)
			node[num].Right = node[root].Right;
		node[root].Right = &node[num];
	}
}
inline int max(const int a, const int b)
{
	return a > b ? a : b;
}
int GetDepth(NODE *pRoot)
{
	if(!pRoot)
		return 0;
	return max(GetDepth(pRoot->Left), GetDepth(pRoot->Right)) + 1;
}
int main()
{
	int n,i;
	int root,num,r;//r为1表示左节点,0表示右节点
	int nLen;
	while(scanf("%d", &n) != EOF)
	{
		memset(node, 0, sizeof(node));
		nLen = 0;
		for(i = 0; i < n; ++i)
		{
			scanf("%d %d %d", &r, &root, &num);
			Add(root, num, r);
		}
		nLen = GetDepth(&node[0]);//数据输入保证以0作为根节点
		printf("树的深度为:%d\n", nLen);
	}
}

2、求二叉树中相距最远的两个节点之间的距离
这里定义的距离可以是节点数,可以是边树,这个关系不大。这里假设距离的定义是节点数,即一个节点的距离是1.
两种情况:要么是根节点的左子树和右子树的最大距离之和。要么就是左子树里面的最大距离或者右子树里面的最大距离。

#include<stdio.h>
#include<string.h>
struct NODE
{
	int MaxLeft;
	int MaxRight;
	NODE *Left;
	NODE *Right;
};
const int N = 20;
NODE node[N];
int MaxLen = 0;
//Add函数和max函数如前面定义
int FindMaxLen(NODE *pRoot)
{
	if(!pRoot)
		return -1;
	//左子树
	if(!pRoot->Left)
		pRoot->MaxLeft = 0;
	else
	{
		FindMaxLen(pRoot->Left);
		pRoot->MaxLeft = max(pRoot->Left->MaxLeft, pRoot->Left->MaxRight) + 1;
	}
	//右子树
	if(!pRoot->Right)
		pRoot->MaxRight = 0;
	else
	{
		FindMaxLen(pRoot->Right);
		pRoot->MaxRight = max(pRoot->Right->MaxLeft, pRoot->Right->MaxRight) + 1;
	}
	MaxLen = max(pRoot->MaxLeft + pRoot->MaxRight + 1, MaxLen);//如果距离的定义是边,则这里不需要加1.
}
int main()
{
	int n,i;
	int root,num,r;//r为1表示左节点,0表示右节点
	while(scanf("%d", &n) != EOF)
	{
		memset(node, 0, sizeof(node));
		MaxLen = 0;
		for(i = 0; i < n; ++i)
		{
			scanf("%d %d %d", &r, &root, &num);
			Add(root, num, r);
		}
		FindMaxLen(&node[0]);//数据输入保证以0作为根节点
		printf("树中两个节点的最大距离为:%d\n", MaxLen);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值