二叉樹的實現(2)鏈表

本文是接上一篇文章寫得。

這個結構體存放了樹根的數據,以及指向左子樹和右子樹的指針。

struct tree
{
   int data;
   struct tree *left;
   struct tree *right;
};

主要用三個函數
btree insert_node( btree root ,int value)
btree creatbtree( int *data,int len )
void printbtree(btree root)
完成實現。

接下來是實現的過程

#include<stdio.h>
#include<stdlib.h>
struct tree
{
   int data;
   struct tree *left;
   struct tree *right;
};
typedef struct tree treenode;
typedef treenode *btree;
btree insert_node( btree root ,int value)
   {
    btree newnode;
    btree current;
    btree back;
     
       newnode = (btree ) malloc(sizeof(treenode));
         newnode->data = value;
         newnode->left = NULL;
         newnode->left = NULL;
      
      if( root == NULL )
         { 
             return  newnode;
         }
      else
         {
           
           current = root;
             while(current != NULL )
                       {
                         back =  current;
                          if( current->data > value )
                                current =  current->left;
                          else
                                current =  current->right;
                                    
			}
              if(back->data > value)
                back->left =newnode;
              else
                back->right =newnode;
                
         }
         return root;
   }

btree creatbtree( int *data,int len )
{
   btree root = NULL;
   int i;
    for( i = 0; i < len ; i++)
       {
         root = insert_node( root , data[i] );
       }
     return root;
}
void printbtree(btree root)
 {
    btree ptr;
    ptr = root->left;
    printf("輸出左子樹\n");
    while( ptr != NULL )
          {
           printf("[%2d]\n",ptr->data);
              ptr = ptr->left;
         }
 ptr = root->right;
    printf("輸出右子樹\n");
    while( ptr != NULL )
          {
           printf("[%2d]\n",ptr->data);
              ptr = ptr->right;
         }
 }
int main()
{
   btree root = NULL;
   int data[10] ={5,6,4,8,2,3,7,1,9};
    root = creatbtree(data,9);
    printf("樹的結點內容\n");
    printbtree(root);      
   return 0 ; 
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章