注册 登录
编程论坛 数据结构与算法

程序纠错——数据结构二叉树求结点最大值(C语言)

CHTEARS 发布于 2014-10-29 14:11, 613 次点击
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct node
{ elemtype data;
  struct node *lchild,*rchild;
 }BTNode,*BTree;
BTree CreateBTree(BTree &T)
{
    int number;
    if(number!=0)
    {scanf("%d",&number);
        T=(BTNode*)malloc(sizeof(BTNode));      
        T->data=number;
        CreateBTree(T->lchild);  
        CreateBTree(T->rchild);   
 }
}
int MAX(BTree BT)
{int m;
if(BT!=NULL)
m=BT->data;
if(BT->data>m)
m=BT->data;
MAX(BT->lchild);
MAX(BT->rchild);
return m;
}
void main()
{BTree T;
int n;
CreateBTree(T);
n=MAX(T);
printf("%d",n);
}
1 回复
#2
soulmate10232014-10-30 21:44
我觉得你的代码里面问题还挺多,帮你写了一个,你可以参考下:基本和你的思路一致
程序代码:
#include<stdio.h>
#include<stdlib.h>
int i=0,a[100]={0};
int max=0;
typedef struct tnode{
        int date;
        struct tnode *lchild;
        struct tnode *rchild;
        }tnode;
        
void creat_tree(tnode *&p){
    // printf("OK\n");
     if(a[i]!=-1){    //以结点为-1 表示无结点
     p=(tnode *)malloc(sizeof(tnode));
     p->date=a[i];
     p->lchild=NULL;
     p->rchild=NULL;
     i++;
     }
     else
     {i++;
     return ;
     }
     creat_tree(p->lchild);
     creat_tree(p->rchild);
     }
     
int max_node(tnode *p){
   
    if(p==NULL) {printf("errer!"); return 0;}
    else
    {
        if(p->date>max) max=p->date;
        if(p->lchild) max_node(p->lchild);
        if(p->rchild) max_node(p->rchild);
        return max;
}
}

int main()
{
    int max_last;
    printf("please input the  number of every node:(以回车结束)\n");
    for(i=0;;i++)      
    {scanf("%d",&a[i]);
     if((getchar())=='\n') break;
     }
    i=0;
    tnode *p;
    creat_tree(p);
    max_last=max_node(p);
    printf("the last max is:%d\n",max_last);
    system("pause");
    return 0;
}
1