[英]Finding the maximum element in a Binary tree using an inorder traversal
void inorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
max=t->value;
if (t->l != NULL)
{
inorder(t->l);
if(max<t->value)
{
max=t->value;
}
}
if (t->r != NULL)
{
inorder(t->l);
if(max<t->value)
{
max=t->value;
}
}
printf("max=%d\n",max);
}
I am trying to implement an inorder traversal to find the maximum element in a binary tree. 我正在尝试实现有序遍历以在二叉树中找到最大元素。 The code that I have written doesn't seem to return a result. 我编写的代码似乎没有返回结果。 By the way, the max variable i used, was declared as a global variable and initialized at zero. 顺便说一句,我使用的最大变量被声明为全局变量,并初始化为零。 Can anyone tell me where I'm going wrong here? 谁能告诉我我要去哪里错了? Thank you before hand! 先谢谢你!
max=t->value;
sets value with no condition. 无条件设置值。 @David van rijn @戴维·范·赖恩
void inorder(const struct btnode *t) {
if (root == NULL) {
printf("No elements in a tree to display");
return;
}
if(max<t->value) { // Add test
max=t->value;
}
if (t->l != NULL) {
inorder(t->l);
}
if (t->r != NULL) {
// inorder(t->l); Wrong leaf.
inorder(t->r);
}
// Best to print from calling routine
// printf("max=%d\n",max);
}
void foo(const struct btnode *t) {
max = INT_MIN; // Set to minimum `int` value.
inorder(t);
printf("max=%d\n",max);
}
OP mentioned that code crashes. OP提到代码崩溃。 Certainly this was because of the wrong leaf was traversed in if (t->r != NULL) { inorder(t->l);
当然,这是因为if (t->r != NULL) { inorder(t->l);
and t->l
was NULL
. 并且t->l
为NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.