在树中搜索(树不是 BST)
Searching in a tree (tree is not BST)
#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;
}
Returns树高
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;
}
问题出在你的搜索功能上,一个简单的错字
if(curr==level)
{
if(root->data==num)
printf("Found %d at level %d\n",root->data,level);
exit(-1);
else printf("Not Found\n");
}
您没有使用赋值运算符来比较值,它总是会打印一个值。
#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;
}
Returns树高
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;
}
问题出在你的搜索功能上,一个简单的错字
if(curr==level)
{
if(root->data==num)
printf("Found %d at level %d\n",root->data,level);
exit(-1);
else printf("Not Found\n");
}
您没有使用赋值运算符来比较值,它总是会打印一个值。