【发布时间】:2025-12-24 22:35:11
【问题描述】:
下面我写了一段代码来回答这个问题。你请告诉我 1) 如果您在我的代码中发现任何缺陷 2) 任何其他最佳解决方案?
问题: 关于Tree数据结构的问题,打印每一层总和(层总和=兄弟数据总和)?
struct tree{
int data;
struct *left;
struct *right;
};
API 原型是 void EachLevelSum(struct tree *root);
我的答案是
void EachLevelSum(struct tree *root )
{
static int level=0;
static int a[100] = {0}; // I am assuming , at MAX 100 levels in tree
if( root == NULL )
{
return;
}
else
{
a[level += root->data;
level++;
EachLevelSum(root->left);
level--;
level++;
EachLevelSum(root->right);
level--;
if( level == 0 )
{
int i;
for( i=0; i<100 && a[i]!=0 ; i++)
{
printf("\n level: %d sum = %d", i, a[i] );
}
}
}
}
【问题讨论】:
-
EachLevelSum 中的第 12 行有一个错字
a[level +=需要是a[level] += -
你有没有想过定义一个增广树,即每个节点都会存储这个级别的总和,并且每当树更新时它都会更新。然后查询它只是查看根和的简单问题:)
标签: c algorithm recursion tree