回 帖 发 新 帖 刷新版面

主题:二叉树帮忙改过

有三个错误,但我不知道怎么改希望高手帮忙
#include<stdlib.h>

struct tree                //声明树的结构
{
     struct tree *left;
     int data;
     struct tree *right;
};

typedef struct tree treenode;
type treenode *b_tree;             //声明二叉树链表

//插入二叉树的节点
b_tree insert_node(b_tree root,int node)
{
     b_tree newnode;
     b_tree currentnode;
     b_tree parentnode;
     
     newnode=(b_tree)malloc(sizeof(treenode));     //建立新节点的内存空间
     newnode->data=node;
     newnode->right=NULL;
     newnode->left=NULL;

     if(root==NULL)
          return newnode;
     else
     {   currentnode=root;
          while(currentnode!=NULL)
          {   parentnode=currentnode;
               if( currentnode->data>node)
                    currentnode=currentnode->left;
               else   currentnode=currentnode->right;
          }
          if(parentnode->data>node)
               parentnode->left=newnode;
          else  parentnode->right=newnode;
     }
     return root;
}

// 建立二叉树
b_tree create_btree(int *data,int len)
{
     b_tree root=NULL;
     int i;

     for(i=0;i<len;i++)
          root=insert_node(root,data[i]);
     return root;
}

//二叉树中序遍历
void inorder(b_tree point)
{
     if(point!=NULL)
     {
          inorder(point->left);
          printf("%d",point->data);
          inorder(point->right);
     }
}

//主程序
int main( )
{
     b_tree root=NULL;
     int i,index;
     int value;
     int nodelist[20];
     printf("\n pleaase input the elements of binary tree(exit for 0 ):\n");
     index=0;

     //读取数值存到数组中
     scanf("%d",&value);
     
     while(value!=0)
     {
          nodelist[index]=value;
          index=index+1;
          scanf("%d",&value);
     }
     //建立二叉树
     root=create_btree(nodelist,index);

     //中序遍历二叉树
     printf("\nThe inorder traversal result is :");
     inorder(root);
     printf("\n");
}

 

回复列表 (共2个回复)

沙发

#include <stdio.h>
#define null 0
#define LXM struct lxm
#define LEN sizeof(struct lxm)
struct lxm
{ int a;
  struct lxm *l;
  struct lxm *r;
};
LXM *initial()
{int b;
 LXM *p;
 p=(LXM*)malloc(LEN);
 p->l=null;
 p->r=null;
 scanf("%d",&b);
  if(b==-1) return null;
   p->a=b;
   p->l=initial();
   p->r=initial();
 return p;

}
void mid(LXM *h)
{if( h==null)
  return;
 mid(h->l);
 printf("%3d",h->a);
 mid(h->r);

}
main()
{LXM *h;
 h=initial();
 mid(h);
}
输入 1 2 4 -1 -1 5 -1 -1 3 6 -1 -1 7 -1 -1回车可构建1 2 3 4 5 6 7从上到下,从左到右的顺序的二叉树
试试这个初始化程序

板凳


谢谢,不过似乎我的略在不同啊,呵呵。不过多一种做法真的不错我会试试的谢谢啊

我来回复

您尚未登录,请登录后再回复。点此登录或注册