binary tree

binary tree

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 typedef  struct tnode{
  5          int data;
  6          struct tnode *left;
  7          struct tnode *right;
  8 }tnode,*tree;
  9 
 10  void createtree(tree *t, int d){
 11         tnode *tn=(tnode *)malloc( sizeof(tnode));
 12         tnode ** root;
 13         (*tn).data = d;
 14         (*tn).right = 0;
 15         (*tn).left = 0;
 16          if(!(*t)){
 17                 *t = tn;
 18                 root = *t;
 19         }
 20          else{
 21         root = *t;
 22                  while(1){
 23                          if((**t).data < d){
 24                                  if((**t).right){
 25                                         *t = (**t).right;
 26                                          continue;
 27                                 }
 28                                  else{
 29                                         (**t).right = tn;
 30                                          break;
 31                                 }
 32                         }
 33                          else  if((**t).data >= d){
 34                                  if((**t).left){
 35                                         *t =(**t).left;
 36                                          continue;
 37                                 }
 38                                  else{
 39                                         (**t).left = tn;
 40                                          break;

 41                                 }
 42                         }
 43                 }
 44         }
 45         *t = root;
 46 }
 47  void inorder(tree t)
 48 {
 49          if(t){
 50                 inorder((*t).left);
 51                 printf("%d\n",(*t).data);
 52                 inorder((*t).right);
 53         }
 54 }
 55  void main()
 56 {
 57          int i;
 58         tree t=0;
 59         printf("input number:0 exit\n");
 60         scanf("%d",&i);
 61          while(i != 0){
 62                 createtree((&t),i);
 63                 scanf("%d",&i);
 64         }
 65         printf("the data is:\n");
 66         inorder(t);
 67         printf("\n");
 68 }

你可能感兴趣的:(binary tree)