編寫一個判斷給定二叉樹是否為二叉排序樹的算法,設二叉樹用二叉鏈表存儲


問題分析:

本程序要求實現判定一棵二叉樹是否為二叉排序樹。為實現上述功能,需要解決的關鍵問題是:建立一棵二叉樹及判定二叉樹過程。

概要設計:

建立一個以二叉鏈表方式存儲的二叉樹,輸入結點信息時按照完全二叉樹的結點順序輸入。由於一棵二叉排序樹中序遍歷后的序列是遞增有序的,因此可利用中序遍歷一棵二叉樹后的序列是否遞增有序來判斷是否為二叉排序樹。

詳細設計:

建立二叉樹時,按照完全二叉樹的結點順序輸入,“1”表示虛結點,“0”表示輸入結束。

若不是虛結點時,則建立一個新結點,並且將其作為左孩子或右孩子結點連接到它的父結點上(第一個結點無父結點);若是虛結點,則將空結點(NULL)作為左孩子或右孩子結點連接到它的父節點上。

判定二叉樹時,中序遍歷整棵二叉樹,訪問根結點時將根結點信息存入一個數組中,以用來比較中序遍歷后序列是否為空。比較數組元素時,從下標為0的數組元素開始比較,先將下標為i=0的a[i]與下標為1的a[i+1]比較,如果a[i]>a[i+1],則結束比較,即該二叉樹不是二叉排序樹,否則繼續比較,直至比較完整個數組元素。

代碼如下:

 1 #include "stdafx.h"
 2 #include<stdlib.h>
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 #include"string"
 6 #include"malloc.h"
 7 #define max 100
 8 typedef struct node {
 9     int data;
10     node *lchild, *rchild;
11 }Bitree;
12 Bitree *B[max];
13 int temp = 0;
14 int Btree[max];
15 
16 void Inorder(Bitree *T) {     //中序遍歷二叉樹,並將每個結點數據存入數組中
17     if (T != NULL) {
18         Inorder(T->lchild);
19         printf("%d\t", T->data);
20         Btree[temp] = T->data;
21         temp++;
22         Inorder(T->rchild);
23     }
24 }
25 int Judgesort_bitree(int Btree[]) {    //判斷是否是二叉排序樹
26     int i, sign = 1;
27     for (i = 0; i<temp - 1; i++) {
28         if (Btree[i]>Btree[i + 1]) {
29             sign = 0;
30             break;
31         }
32     }
33     return sign;
34 }
35 void Judgeout(int a) {   //判斷輸出
36     if (a == 1)
37         printf("給定二叉樹是二叉排序樹!\n");
38     if (a == 0)
39         printf("給定二叉樹不是二叉排序樹!\n");
40 }
41 
42 Bitree *Creatree() {    //建立二叉樹
43     Bitree *T, *S;
44     int ch;
45     int front, rear, sign;
46     sign = 0;
47     front = 0;
48     rear = -1;
49     T = NULL;
50     printf("建立二叉樹(1表示虛結點,0表示輸入結束):\n");
51     scanf_s("%d", &ch);
52     while (ch != 0) {
53         if (ch != 1) {    //輸入結點不是虛結點
54             S = (Bitree *)malloc(sizeof(Bitree));
55             S->data = ch;
56             S->lchild = S->rchild = NULL;
57             rear++;
58             B[rear] = S;
59             if (rear == front) {
60                 T = S;
61                 sign++;
62             }
63             else {
64                 if (sign % 2 == 1)  //尋找父結點
65                     B[front]->lchild = S;
66                 if (sign % 2 == 0) {
67                     B[front]->rchild = S;
68                     front++;
69                 }
70                 sign++;
71             }
72             //printf("\n");
73             //Judgeout(Judgesort_bitree(Btree));
74         }
75         else {        //輸入結點為虛結點
76             if (sign % 2 == 0)
77                 front++;
78             sign++;
79         }
80         scanf_s("%d", &ch);
81     }
82     return T;
83 }
84 void main() {
85     Bitree *T;
86     T = Creatree();
87     printf("中序遍歷:\n");
88     Inorder(T);
89     printf("\n");
90     Judgeout(Judgesort_bitree(Btree));
91     system("pause");//便於觀察
92 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM