先来点基础的,更多扩展,请猛击: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);
}
}