資料結構與演算法題目集7-3——樹的同構
阿新 • • 發佈:2018-12-05
我的資料結構與演算法題目集程式碼倉:https://github.com/617076674/Data-structure-and-algorithm-topic-set
原題連結:https://pintia.cn/problem-sets/15/problems/711
題目描述:
知識點:遞迴
思路:遞迴判斷兩棵樹是否同構
遞迴終止條件:
(1)當head1 == -1 且head2 == -1時,兩棵樹都是空樹,返回true。
(2)當head1 == -1 且head2 != -1時,一棵是空樹,另一棵不是空樹,返回false。
(3)當head1 != -1 且head2 == -1時,一棵是空樹,另一棵不是空樹,返回false。
遞迴過程:
(4)當head1和head2均不為-1時,
如果head1的左子樹和head2的左子樹同構,且head1的右子樹和head2的右子樹同構,返回true。
如果head1的左子樹和head2的右子樹同構,且head1的右子樹和head2的左子樹同構,返回true。
如果以上兩種情況都不滿足,返回false。
時間複雜度和空間複雜度均是O(N)。
注意點:用scanf("%c", &data);讀取輸出字元時,需要用getchar()讀取中間的空格符以及行末的換行符。
C++程式碼:
#include<iostream> using namespace std; struct node { char data; int lchild, rchild; }; int N; node Node1[10], Node2[10]; int read(node Node[]); bool judge(int head1, int head2); int main() { int head1 = read(Node1); int head2 = read(Node2); if(judge(head1, head2)) { printf("Yes\n"); } else { printf("No\n"); } return 0; } int read(node Node[]) { scanf("%d", &N); getchar(); char data, lchild, rchild; bool show[N]; fill(show, show + N, false); for(int i = 0; i < N; i++) { scanf("%c", &data); getchar(); scanf("%c", &lchild); getchar(); scanf("%c", &rchild); getchar(); Node[i].data = data; if(lchild == '-') { Node[i].lchild = -1; } else { Node[i].lchild = lchild - '0'; show[lchild - '0'] = true; } if(rchild == '-') { Node[i].rchild = -1; } else { Node[i].rchild = rchild - '0'; show[rchild - '0'] = true; } } for(int i = 0; i < N; i++) { if(!show[i]) { return i; } } return -1; } bool judge(int head1, int head2) { if(head1 == -1 && head2 == -1) { return true; } else if(head1 == -1 && head2 != -1) { return false; } else if(head1 != -1 && head2 == -1) { return false; } else { if(Node1[head1].data != Node2[head2].data) { return false; } else { return (judge(Node1[head1].lchild, Node2[head2].lchild) && judge(Node1[head1].rchild, Node2[head2].rchild)) || (judge(Node1[head1].lchild, Node2[head2].rchild) && judge(Node1[head1].rchild, Node2[head2].lchild)); } } }
C++解題報告: