二叉树的相似,是指俩二叉树有相似的结构,同样的节点位置可以有不同的值,但要么都是空节点,要么都不是空节点。只要有一个节点位置不相似,即一个是空节点,另一个是非空节点,则整个二叉树都不相似。下面给出完整代码,包括根据逗号表达式建立二叉树creatBiTree,输出二叉树displayBiTree,比较二叉树是否相似compareBiTree三个被调用函数。完整代码如下:
#include<iostream>
#include<stdio.h>
using namespace std;
#define STACKDEPTH 10
struct BiTreeNode {
char value;
BiTreeNode* leftChild;
BiTreeNode* rightChild;
};
void creatBiTree(BiTreeNode *& biTreeRoot,char * ptChar) {
struct {
BiTreeNode* nodes[STACKDEPTH];
int indexTop = -1;
}stack;
int leftRight = 0;// 1 is left ,2 is right
BiTreeNode* ptNew = NULL;
char c = *ptChar;
while (c != '\0') {
if (c >= 'A' && c <= 'Z') {
ptNew = new BiTreeNode;
ptNew->value = c;
ptNew->leftChild = ptNew->rightChild = NULL;
if (biTreeRoot == NULL)
biTreeRoot = ptNew;
else if (leftRight == 1)
stack.nodes[stack.indexTop]->leftChild = ptNew;
else if (leftRight == 2)
stack.nodes[stack.indexTop]->rightChild = ptNew;
}
else if (c == '(') {
stack.indexTop++;
stack.nodes[stack.indexTop] = ptNew;
leftRight = 1;
}
else if (c == ',')
leftRight = 2;
else if (c == ')')
stack.indexTop--;
ptChar++;
c = *ptChar;
}
}
void displayBiTree(BiTreeNode *&biTreeRoot) {
if (biTreeRoot == NULL)
return;
cout << biTreeRoot->value;
if (biTreeRoot->leftChild != NULL || biTreeRoot->rightChild != NULL) {
cout << '(';
displayBiTree(biTreeRoot->leftChild);
if (biTreeRoot->rightChild != NULL) {
cout << ',';
displayBiTree(biTreeRoot->rightChild);
}
cout << ')';
}
}
bool compareBiTree(BiTreeNode *&biTreeRootA, BiTreeNode*& biTreeRootB) {
if (biTreeRootA == NULL && biTreeRootB == NULL)
return true;
if (biTreeRootA == NULL || biTreeRootB == NULL)
return false;
bool left = compareBiTree(biTreeRootA->leftChild, biTreeRootB->leftChild);
if (left == false)
return false;
else {
bool right = compareBiTree(biTreeRootA->rightChild, biTreeRootB->rightChild);
return left && right;
}
}
int main() {
char arrayA[] = "A(B,C(,D))", arrayB[] = "D(E,F(,K))";
BiTreeNode* biTreeA = NULL, * biTreeB = NULL;
char* ptChar = arrayA;
creatBiTree(biTreeA,ptChar);
ptChar = arrayB;
creatBiTree(biTreeB,ptChar);
cout << "arrayA ; ";
for (ptChar = arrayA; *ptChar != '\0'; ptChar++)
cout << *ptChar;
cout << endl << "arrayB : ";
for (ptChar = arrayB; *ptChar != '\0'; ptChar++)
cout << *ptChar;
cout << endl;
cout << "biTree A ; "; displayBiTree(biTreeA); cout << endl;
cout << "biTree B : "; displayBiTree(biTreeB); cout << endl;
cout << "A is similar with B ? ";
cout << (compareBiTree(biTreeA, biTreeB) ? "true" : "false" )<< endl;
return 0;
}
测试结果如下:
谢谢阅读