【发布时间】:2015-09-14 01:35:09
【问题描述】:
我必须用 C 语言编写一个算法,该算法接受二叉搜索树的输入。该练习将访问定义为“左访问”,即从子树的根开始并尽可能向左走。同样,它定义了“正确的访问”。练习要求打印左访问严格大于右访问的三个键。它还要求按升序打印此密钥,并且该算法必须在线性时间内工作,因此我必须实现一个类似按顺序访问的算法。现在,我编写了一个在线性时间内工作的算法,但在某些情况下它不能作为按顺序访问,因此打印的密钥不是按升序排列的,但我不知道如何管理克服这个障碍。如何在不首先实现左右递归的情况下比较左访问和右访问?
#include<stdio.h>
#include<stdlib.h>
typedef struct _node {
int dato;
struct _node *left;
struct _node *right;
}node;
typedef struct _ret {
int sin;
int des;
}res;
node *inserisci(node *root, int insert)
{
if(root==NULL) {
node * new=(node*)malloc(sizeof(node));
new->left=NULL;
new->right=NULL;
new->dato=insert;
return new;
}
if(root->dato < insert) root->right =inserisci(root->right,insert);
else root->left = inserisci(root->left,insert);
return root;
}
res somma(node * u)
{
res ret; res ciao_sx; res ciao_dx;
if(u==NULL) return;
if(u->left==NULL && u->right==NULL)
{
ret.sin=0;
ret.des=0;
return ret;
}
if(u->left!=NULL && u->right!=NULL)
{
ciao_sx=somma(u->left);
ret.sin= ciao_sx.sin+1;
ciao_dx=somma(u->right);
ret.des= ciao_dx.des+1;
if(ret.sin > ret.des )
{
printf("%d\n",u->dato);
}
return ret;
}
if(u->left!=NULL && u->right==NULL)
{
ciao_sx=somma(u->left);
ret.sin= ciao_sx.sin+1;
ret.des= 0;
printf("%d\n",u->dato);
return ret;
}
if(u->left==NULL && u->right !=NULL)
{
ciao_dx=somma(u->right);
ret.des= ciao_dx.des +1;
ret.sin=0;
return ret;
}
}
int main()
{
int n,i,x;
scanf("%d",&n);
node *root=NULL;
for(i=0;i<n;i++) {
scanf("%d",&x);
root=inserisci(root,x);
}
somma(root);
return 0;
}
【问题讨论】:
-
把代码也贴出来
-
或许还能学会使用调试器
-
我不知道如何发布代码并且我编写的代码有效,没有错误。你能解释一下如何发布代码吗?谢谢!
-
复制粘贴并使用代码格式选项
-
@GiovanniMauro 只需复制并粘贴代码,然后使用鼠标选择代码并按 ctrl-k。
标签: c algorithm binary-search-tree