C,无复杂代码,无详细注释,自写,请读者视情参考
思想:
我们在求树的深度的时候,一般采用两种方法,一种是递归计算子树的深度,一种是非递归遍历树,取栈顶指针的最远处。
对于第一种方法,其思想是对某一个节点,比较其左子树的深度和右子树的深度,取最长便是当前节点的深度。
那么是否可以利用这个比较的间隙,将左子树的深度和右子树的深度加在一起,得出当前节点的直径呢?如果可以,那么所有节点的直径中取最大值,便是一整棵树的直径了。
所需知识:
C,二叉树,树的深度算法
途径:
在树的深度算法中插入一个计算直径的语句,保存直径的最大值。
举例:
无
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)
#define ElemType int
#define OK 1
#define ERROR 0
#define MaxNodeCount 50
typedef int Status;
typedef struct BiTreeNode
{
ElemType data;
struct BiTreeNode* lchild;
struct BiTreeNode* rchild;
}BiTreeNode, * Bitree;
Bitree Queue[MaxNodeCount];
int front = 0, rear = 0, last = 0, lev = 0;
int wid[MaxNodeCount] = { 0 };
Bitree found = NULL;
int fData = 0;
//T 参数为被插入的节点,data 为插入数据,优先左插
void LchildFirstInsert(Bitree& T, int data) {
Bitree P = (BiTreeNode*)malloc(sizeof(BiTreeNode));
P->data = data;
P->lchild = NULL;
P->rchild = NULL;
if (T == NULL) {
T = P;
}
else {
if (T->lchild == NULL) {
T->lchild = P;
}
else {
T->rchild = P;
}
}
}
Status LevelOrder(Bitree& T, Status(*Visit)(Bitree&)) {
if (T == NULL)
{
return ERROR;
}
Bitree p = T;
front = -1; rear = -1; last = 0; lev = 0, wid[0] = 1;
Queue[++rear] = p;
while (front < rear) {
p = Queue[++front];
if (!Visit(p))return OK;
if (p->lchild) {
Queue[++rear] = p->lchild;
}
if (p->rchild)
{
Queue[++rear] = p->rchild;
}
if (front == last)
{
++lev;
wid[lev] = rear - last;
last = rear;
}
}
return OK;
}
Status Find(Bitree& T) {
if (fData == T->data) {
found = T;
return ERROR;
}
return OK;
}
Status PrintData(Bitree& T) {
printf("%d ", T->data);
return OK;
}
Status DoNothing(Bitree& T) {
return OK;
}
Status main() {
Bitree T = NULL;
int n;//有n个结点
int x, y;//二叉树中x为y的父节点。x第一次出现时y为左孩子
LchildFirstInsert(T, 1);
scanf("%d", &n);
for (int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
fData = x;
found = NULL;
LevelOrder(T, Find);
LchildFirstInsert(found, y);
}
LevelOrder(T, DoNothing);
int maxWidth = 0;
for (int i = 0; wid[i]; i++) {
maxWidth = wid[i] > maxWidth ? wid[i] : maxWidth;
}
printf("%d", maxWidth);
}
Description
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
1
/
2 3
/ \
4 5
答案为3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
输入格式
共n行。
第一行一个整数n,表示有n个结点,编号为1至n。
第二行至第n行,每行有两个整数x和y,表示在二叉树中x为y的父节点。x第一次出现时y为左孩子
输出格式
输出二叉树的直径。
输入样例
5
1 2
1 3
2 4
2 5
输出样例
3
本文介绍了一种在求解二叉树深度的过程中同时计算直径的方法。通过在原有树的深度算法中插入计算直径的步骤,找出所有节点直径的最大值,从而得到整棵树的直径。以C语言实现,无复杂代码和详细注释,适用于理解二叉树直径问题的解决思路。
1436

被折叠的 条评论
为什么被折叠?



