题目链接:https://pintia.cn/problem-sets/15/problems/712
1.分别建立两棵二叉搜索树
建立:
Tree Initial(int N) { Tree T= (Tree)malloc(sizeof(struct TreeNode) * (N)); scanf("%d", &T[0].num); T[0].left = Null; T[0].right = Null; int i, root; for (i = 1;i < N;i++) { root = 0; scanf("%d", &T[i].num); T[i].left = Null; T[i].right = Null; while (1) { if (T[i].num < T[root].num) { if (T[root].left == Null) { T[root].left = i; break; } else root = T[root].left; } else { if (T[root].right == Null) { T[root].right = i; break; } else root = T[root].right; } } } return T; }
- 非递归:用两个队列来层序遍历,若遇到不相同的元素就不相同
void Compare(Tree T1, Tree T2) { SQueue Q1 = (SQueue)malloc(sizeof(struct Queue)); SQueue q1 = Q1; SQueue Q2 = (SQueue)malloc(sizeof(struct Queue)); SQueue q2 = Q2; q1->next = NULL; q1->num = -1; in(Q1, 0); q2->next = NULL; q2->num = -1; in(Q2, 0); while (Q1->next&&Q2->next) { int number1 = out(Q1); int number2 = out(Q2); /*if (T[number].left == Null && T[number].right == Null) { printf("%d", number); count--; if (count) printf(" "); }*/ if(T1[number1].num!=T2[number2].num){ printf("No "); return; } if (T1[number1].left != Null) in(Q1, T1[number1].left); if (T1[number1].right != Null) in(Q1, T1[number1].right); if (T2[number2].left != Null) in(Q2, T2[number2].left); if (T2[number2].right != Null) in(Q2, T2[number2].right); } printf("Yes "); return; }
- 递归:根相同,递归比较左右子树
int Compare(Tree T1, Tree T2,int root1,int root2) { if (root1 == Null && root2 == Null) return 1; if (T1[root1].num == T2[root2].num) { return Compare(T1, T2, T1[root1].left, T2[root2].left) && Compare(T1, T2, T1[root1].right, T2[root2].right); } else return 0; }
2.建立一棵树,再判别其他序列是否与该树一致
思路:树结点多一个flag域,第一棵树建立起来后,在树上搜索要判定序列中的每一个结点,如果搜索经过的结点有未出现的结点,则一定不是同一棵树。因为如果遇到了未出现的结点,则该结点一定插在这里的,而不是后面才插进来。