Home > Back-end >  Want to compare two binary tree similarity, the premise is to build two binary trees, but this secti
Want to compare two binary tree similarity, the premise is to build two binary trees, but this secti

Time:09-30

#include
#include
#include
using namespace std;

Typedef struct bTree {
Char data;
LCH struct bTree * and * RCH;
} bTree;

Creat bTree * * p) (bTree {
Char c;
The scanf (" % c ", & amp; C);
If (c==' ')
P=NULL;
The else {
P=(bTree *) malloc (sizeof (bTree));
p-> Data=https://bbs.csdn.net/topics/c;
p-> LCH=creat (p - & gt; LCH);
p-> RCH=creat (p - & gt; RCH);
}
return p;
}

//in order o
Void printMid (bTree * p) {
If (p) {
PrintMid (p - & gt; LCH);
Cout The data;
PrintMid (p - & gt; RCH);
}
}

//determine binary tree T1, T2 is similar, is to return true, no returns false
Bool SimilarTree (bTree * T1, bTree * T2) {
if(! T1) {//T1 is empty tree
if(! T2)
return true;//T2 is empty tree
The else
return false;
}
The else {//T1 is empty tree
if(! T2) return false.
The else {//T2 non-null tree
If (SimilarTree (T1 - & gt; LCH, T2 - & gt; LCH) & amp; & SimilarTree (T1 - & gt; RCH, T2 - & gt; RCH))
return true;
The else
return false;
}
}
}

Int main () {
BTree * B1=NULL, * B2=NULL;
Cout<" B1: build a binary tree "& lt; B1=creat (B1);
Cout<" B2: build binary tree "& lt; B2=creat (B2);
Cout<" Please make sure you enter information: "& lt; Cout<" Sequence traversal in B1: ";
PrintMid (B1);
CoutPrintMid (B2);
CoutIf (SimilarTree (B1, B2))
Cout<" B1, B2 is similar to the binary tree "& lt; The else
Cout<" B1, B2 is not similar to the binary tree "& lt; return 0;
}
  • Related