資料結構實驗之查詢一:二叉排序樹 (SDUT 3373)
阿新 • • 發佈:2018-12-11
二叉排序樹(Binary Sort Tree),又稱二叉查詢樹(Binary Search Tree),也稱二叉搜尋樹。
#include <stdio.h> #include <string.h> #include <stdlib.h> struct node{ int data; struct node *l, *r; }; struct node *creat(struct node *root,int x) { if(root == NULL) // 如果 root 是空,表示當前是可以把這個點加進去的,就可以放進去了 { root = new node; root -> data = x; root -> l = NULL; root -> r = NULL; } else { //如果不是,考慮兩種情況 if(x > root -> data) //如果比當前的根節點大,去右子樹找 root -> r = creat(root -> r, x); else root -> l = creat(root -> l, x); // 否則去左子樹找 } return root; //別忘記了返回樹根! }; int ok(struct node *t1, struct node *t2) // 判斷兩個樹是否相同 { if(t1 == NULL && t2 == NULL) // 如果比較到最下層都沒有發現不同的就返回 1 return 1; else if(t1 != NULL && t2 != NULL) // 如果沒有到最下層,繼續向下找 { if(t1 -> data != t2 -> data) // 如果一旦發現不同的,就不滿足了 { return 0; } else if((ok( t1 -> l , t2 -> l) && ok(t1 -> r, t2 -> r))){ // 分別的左子樹、右子樹都要滿足 return 1; } } else return 0; } int a[55]; int b[55]; int main() { int n,m; while(scanf("%d",&n)!=EOF && n) { scanf("%d",&m); struct node *root1,*root2; // 這裡需要樹根節點(指標) for(int i = 0; i < n; i ++) { // 先輸入 scanf("%d",&a[i]); } root1 = new node; root1 -> data = a[0]; // 把根放進去 root1 -> l = root1 -> r = NULL; // 左右結點初始化 for(int i = 1; i < n; i ++){ // 建樹 root1 = creat(root1,a[i]); } while(m --) { for(int i = 0; i < n; i ++){ // 相同的建樹方法 scanf("%d",&b[i]); } root2 = new node; root2 -> data = b[0]; root2 -> l = root2 -> r = NULL; for(int i = 1; i < n; i ++) { root2 = creat(root2,b[i]); } int f = ok(root1,root2); // 比較 if(f)printf("Yes\n"); else printf("No\n"); } } return 0; }