1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <stdbool.h> 4 5 typedef int ElementType; 6 7 struct BinarySearchTreeNode 8 { 9 ElementType Element; 10 struct BinarySearchTreeNode *Left; 11 struct BinarySearchTreeNode *Right; 12 }; 13 14 bool TwoBSTreeIsSame(struct BinarySearchTreeNode *TreeRoot_1,struct BinarySearchTreeNode *TreeRoot_2) 15 { 16 if(!TreeRoot_1 && !TreeRoot_2) 17 return true; 18 if( (TreeRoot_1 && !TreeRoot_2) || (!TreeRoot_1 && TreeRoot_2) || 19 TreeRoot_1->Element != TreeRoot_2->Element) 20 return false; 21 return TwoBSTreeIsSame(TreeRoot_1->Left,TreeRoot_2->Left) && TwoBSTreeIsSame(TreeRoot_1->Right,TreeRoot_2->Right); 22 } 23 24 int main() 25 { 26 struct BinarySearchTreeNode Tree_1[3]; 27 struct BinarySearchTreeNode Tree_2[3]; 28 struct BinarySearchTreeNode Tree_3[3]; 29 30 Tree_1[0].Element = 1; 31 Tree_1[1].Element = 2; 32 Tree_1[2].Element = 3; 33 Tree_1[0].Left = &Tree_1[1]; 34 Tree_1[0].Right = NULL; 35 Tree_1[1].Left = NULL; 36 Tree_1[1].Right = &Tree_1[2]; 37 Tree_1[2].Left = NULL; 38 Tree_1[2].Right = NULL; 39 40 Tree_2[0].Element = 1; 41 Tree_2[1].Element = 3; 42 Tree_2[2].Element = 2; 43 Tree_2[0].Left = &Tree_2[1]; 44 Tree_2[0].Right = NULL; 45 Tree_2[1].Left = &Tree_2[2]; 46 Tree_2[1].Right = NULL; 47 Tree_2[2].Left = NULL; 48 Tree_2[2].Right = NULL; 49 50 Tree_3[0].Element = 1; 51 Tree_3[1].Element = 2; 52 Tree_3[2].Element = 3; 53 Tree_3[0].Left = &Tree_3[1]; 54 Tree_3[0].Right = NULL; 55 Tree_3[1].Left = NULL; 56 Tree_3[1].Right = &Tree_3[2]; 57 Tree_3[2].Left = NULL; 58 Tree_3[2].Right = NULL; 59 60 printf("Tree_1 compare with Tree_2: %d ",TwoBSTreeIsSame(&Tree_1[0],&Tree_2[0])); 61 printf("Tree_1 compare with Tree_3: %d ",TwoBSTreeIsSame(&Tree_1[0],&Tree_3[0])); 62 printf("Tree_3 compare with Tree_2: %d ",TwoBSTreeIsSame(&Tree_3[0],&Tree_2[0])); 63 printf("Tree_3 compare with Tree_3: %d ",TwoBSTreeIsSame(&Tree_3[0],&Tree_3[0])); 64 return 0; 65 } 66 /* 67 68 Tree_1: 1 Tree_2: 1 Tree_3 is as same as Tree_1. 69 ↙ ↙ 70 2 3 71 ↘ ↙ 72 3 2 73 */