數據結構實驗之查找二:平衡二叉樹
TimeLimit: 400MS Memory Limit: 65536KB
SubmitStatistic
根據給定的輸入序列建立一棵平衡二叉樹,求出建立的平衡二叉樹的樹根。
Input
輸入一組測試數據。數據的第1行給出一個正整數N(n <= 20),N表示輸入序列的元素個數;第2行給出N個正整數,按數據給定順序建立平衡二叉樹。
Output
輸出平衡二叉樹的樹根。
Example Input
5
88 70 6196 120
Example Output
70
Hint
Author
xam
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<queue>#include<math.h>#include<iostream>#include<algorithm>using namespace std;typedef struct node{   int data;   int d;   struct node *l,*r;}tree;int deep(tree*root){   if(!root)   return -1;   else   return root->d;}tree* LL(tree*root)//左左情況進行右旋{    tree*p = root->l;    root->l = p->r;    p->r = root;    p->d =max(deep(p->l),deep(p->r))+1;    root->d = max(deep(root->l),deep(root->r))+1;    return p;}tree* RR(tree*root){    tree*p = root->r;    root->r = p-> l;    p->l = root;    p->d =max(deep(p->l),deep(p->r))+1;    root->d = max(deep(root->l),deep(root->r))+1;    return p;}tree* LR(tree*root)//左右情況先進行左旋(右右),然后左旋(左左){    root->l = RR(root->l);    return LL(root);}tree* RL(tree*root){    root->r = LL(root->r);    return RR(root);}tree* creat(tree*root,int x){    if(root==NULL)    {       root = (tree*)malloc(sizeof(tree));       root->d = 0;       root->data = x;       root->l = root->r = NULL;    }    else if(root->data>x)    {         root->l = creat(root->l,x);         if(deep(root->l)-deep(root->r)>1)         {             if(root->l->data>x)             {                root = LL(root);             }             else             {                  root = LR(root);             }         }    }    else if(root->data<=x)    {         root->r = creat(root->r,x);         if(deep(root->r)-deep(root->l)>1)         {              if(root->r->data>x)              {                  root = RL(root);              }              else                root = RR(root);         }    }    root->d = max(deep(root->l),deep(root->r))+1;//及時更新每個節點的深度    return root;}int main(){   int n,i,x;   scanf("%d",&n);   tree*root = NULL;   for(i = 0;i < n;i++)   {      scanf("%d",&x);      root = creat(root,x);   }   printf("%d/n",root->data);  return 0;}/***************************************************User name: jk160505徐紅博Result: AcceptedTake time: 0msTake Memory: 152KBSubmit time: 2017-02-08 15:25:50****************************************************/ 
新聞熱點
疑難解答