二叉排序樹,二叉排序

來源:互聯網
上載者:User

二叉排序樹,二叉排序

二叉排序樹 Time Limit: 1000MS Memory limit: 65536K 題目描述

二叉排序樹的定義是:或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別為二叉排序樹。 今天我們要判斷兩序列是否為同一二叉排序樹

輸入開始一個數n,(1<=n<=20) 表示有n個需要判斷,n= 0 的時候輸入結束。接下去一行是一個序列,序列長度小於10,包含(0~9)的數字,沒有重複數字,根據這個序列可以構造出一顆二叉排序樹。接下去的n行有n個序列,每個序列格式跟第一個序列一樣,請判斷這兩個序列是否能組成同一顆二叉排序樹。(資料保證不會有空樹)輸出樣本輸入
21234567899876543214321567890
樣本輸出
NONO
提示 來源 樣本程式 

建立二叉排序樹,然後比較兩個的先序遍曆


#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{    int data;    struct node *l,*r;};int cnt;struct node *creat(struct node *&root,int a){    if(root==NULL)    {        root=(struct node *)malloc(sizeof(struct node));        root->l=NULL;        root->r=NULL;        root->data=a;    }    else    {        if(a<root->data)            creat(root->l,a);        else            creat(root->r,a);    }};void qianxu(struct node *root,char *str){    if(root)    {        str[cnt++]=root->data;        qianxu(root->l,str);        qianxu(root->r,str);    }}int main(){    int n,i;    char str1[20],str2[20];    while(~scanf("%d",&n))    {        if(n==0)            break;            scanf("%s",str1);           int len=strlen(str1);           struct node *root=NULL;           cnt=0;           for(i=0;i<len;i++)           {              creat(root,str1[i]);           }           qianxu(root,str1);           str1[cnt]='\0';           while(n--)           {               struct node *p=NULL;               scanf("%s",str2);               int len1=strlen(str2);               cnt=0;               for(i=0;i<len1;i++)               {                   creat(p,str2[i]);               }               qianxu(p,str2);               str2[cnt]='\0';               if(strcmp(str1,str2)==0)                printf("YES\n");               else                printf("NO\n");           }    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.