二叉排序樹,二叉排序
二叉排序樹 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;}