将二叉树转换为二叉搜索树

时间:2016-11-12 20:04:25

标签: c data-structures binary-tree binary-search-tree

所以我在这里通过将树的元素复制到数组来将二叉树转换为二进制搜索树。 然后,我对数组进行排序(冒泡排序),然后使用inorder遍历遍历树并将数组元素复制到树中。 一切都工作正常,但函数void inr(Node * root)不像二进制搜索树中那样复制元素我应该按递增顺序(按顺序遍历)获取元素但是我没有得到正确的输出。

#include<stdio.h>
#include<stdlib.h>
   int x=0;
   int l=0;
   typedef struct node
   {
      int data;
      struct node *rlink;
      struct node *llink;
   } Node;
   Node *getnode()
   {
      Node *temp=(Node *)malloc(sizeof(Node));
      return temp;
   }
   int a[10];
   int i=0;
   Node *create(Node *root,int key)
   {
      int c;
      if(root==NULL)
      {
         root=getnode();
         root->rlink=root->llink=NULL;
         root->data=key;
      }
      else
      {
         printf("Enter where you want to enter 1.RIGHT 2.LEFT");
         scanf("%d",&c);
         switch(c)
         {
            case 1:root->rlink=create(root->rlink,key);
                   break;
            case 2:root->llink=create(root->llink,key);
                   break;
            default:printf("Wrong choice");
            break;
         }
     }
     return root;
}

void inorder(Node *root) //to copy the contents  of the tree in the array
{
   if(root!=NULL)
   {
      inorder(root->rlink);
      if(root->data>0) a[i++]=root->data;
      inorder(root->llink);
   }
}

void utu(Node *h) //For inorder traversal
{
   if(h!=NULL)
   {
      utu(h->rlink);
      printf("%d",h->data);
      utu(h->llink);
   }
}

void inr(Node *root) //to copy the elements of sorted array in the tree to make it a BST
{
   if(root==NULL) return;
   else if(root!=NULL)
   {
      inr(root->llink);
      root->data=a[l++];
      inr(root->rlink);
   }
}

void main()
{
   int j=0;
   int temp=0;
   Node *h=NULL;
   h=create(h,5);
   h=create(h,6);
   h=create(h,7);
   h=create(h,8);
   inorder(h);
   count(h);
   printf("%d \n",x);
   printf("\n \n \n");
   for(j=0;j<x;j++)
   {
      printf("%d \n",a[j]);
   }
   for(int i=0;i<x;i++) //bubble sorting of the array obtained by copying the nodes data in the array
   {
      for(j=i+1;j<x;j++)
      {
         if(a[i]>a[j])
         {
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
         }
      }
  }
  utu(h);
  //for(j=0;j<x;j++)
  //{
  //    printf("\n %d \n",a[j]);
  //}
  printf("\n \n");
  //j=maxd(h);
  //printf("%d",j);
  inr(h);
  utu(h);
}

0 个答案:

没有答案
相关问题