#include<stdio.h>
#include<stdlib.h>
它只打印我传递的任何数据,如果可能请建议进行一些优化。
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node= malloc(sizeof(struct node));
node->data=data;
node->left=NULL;
node->right=NULL;
return node;
}
int height(struct node* root) //returns height of a tree
{
int lheight,rheight;
if(root==NULL)return;
else
{
lheight=height(root->left);
rheight=height(root->right);
}
if(lheight>rheight)
return lheight+1;
else return rheight+1;
}
void levelordersearch(struct node* root,int curr,int level,int num)
{
if(root==NULL) return;
if(curr==level)
{
if(root->data=num)
printf("Found %d at level %d\n",root->data,level);
exit(-1);
else printf("Not Found\n");
}
else
{
levelordersearch(root->left,curr+1,level,num);
levelordersearch(root->right,curr+1,level,num);
}
}
void level(struct node* root,int data)
{
int h,i;
h=height(root);
for(i=1;i<=h;i++)
{
levelordersearch(root,1,i,data);
}
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
level(root,90);
return 0;
}
答案 0 :(得分:4)
问题在于你的搜索功能,一个简单的错字
if(curr==level)
{
如果(根 - &GT;数据== NUM)强>
printf("Found %d at level %d\n",root->data,level);
exit(-1);
else printf("Not Found\n");
}
除了比较值之外,您还使用了一个始终打印值的赋值运算符。