本程序来自课本例题,主要包括根据一个字符串数组,即二叉树的逗号表达式,建立二叉树,由函数createBTree完成。然后根据二叉树输出其对应的逗号表达式,由函数displayBTree完成。查找二叉树是否包含某个元素,若包含,返回其所在的行,由函数layerNumber完成。通过该例题,练习了二叉树和递归的知识运用。书写表达式时,无论是否有右孩子节点,都保留了逗号,当然也可以如课本,无右孩子节点,不输出逗号。程序稍微改动下就可以。代码如下:
#include<iostream>
#include<stdio.h>
using namespace std;
#define STACKDEPTH 15
struct BTreeNode {
char value;
BTreeNode* leftChild;
BTreeNode* rightChild;
};
void createBTree(BTreeNode *&bTreeRoot,char *&ptChar) {
struct {
BTreeNode* ptsBiTree[STACKDEPTH];
int indexTop = -1;
}sequStack;
BTreeNode* ptNew = NULL;
char s ;
int leftRight;//1 is left 2 is right
while (*ptChar != '\0') {
s = *ptChar;
if ('A' <= s && s <= 'Z') {
ptNew = new BTreeNode;
ptNew->value = s;
ptNew->leftChild = ptNew->rightChild = NULL;
if (bTreeRoot == NULL)
bTreeRoot = ptNew;
else if (leftRight == 1)
sequStack.ptsBiTree[sequStack.indexTop]->leftChild = ptNew;
else if (leftRight == 2)
sequStack.ptsBiTree[sequStack.indexTop]->rightChild = ptNew;
}
else if (s == '(') {
sequStack.indexTop++;
sequStack.ptsBiTree[sequStack.indexTop] = ptNew;
leftRight = 1;
}
else if (s == ',')
leftRight = 2;
else if (s == ')')
sequStack.indexTop--;
ptChar++;
}
}
void displayBTree(BTreeNode *&bTreeRoot) { // 本查找方法是先序遍历
if (bTreeRoot == NULL)
return;//if binary tree does not exsit,return
cout << bTreeRoot->value;
if (bTreeRoot->leftChild != NULL || bTreeRoot->rightChild != NULL) {
cout << '(';
displayBTree(bTreeRoot->leftChild);
cout << ',';
displayBTree(bTreeRoot->rightChild);
cout << ')';
}
}
int layerNumber(BTreeNode*& bTreeRoot, char m, int layerNum) {
if (bTreeRoot == NULL)
return 0;
if (bTreeRoot->value == m)// 仍然是先序遍历
return layerNum;
if (bTreeRoot->leftChild != NULL || bTreeRoot->rightChild != NULL) {
int left = layerNumber(bTreeRoot->leftChild, m, layerNum + 1);
int right = layerNumber(bTreeRoot->rightChild, m, layerNum + 1);
return left > right ? left : right;
}
else
return 0;
}
int main() {
char array[] = "A(B(D(,G),),C(E,F))";
char* ptChar = array; //c++里只能这样分开定义,要不会出错。
BTreeNode* bTreeRoot = NULL;
createBTree(bTreeRoot,ptChar);
cout << "the char array is :";
for (int i = 0; array[i] != '\0'; i++)
cout << array[i];
cout<< endl<< "binary tree is :";
displayBTree(bTreeRoot);
cout << endl << "节点 value :";
char s;
cin >> s;
int i = layerNumber(bTreeRoot,s,1);
if (i == 0)
cout << "the char is not in the binary tree ." << endl;
else
cout << "the char is in the " << i << "th layer ." << endl;
return 0;
}
测试结果如下:
谢谢阅读。数据结构很难。日积月累,坚持不懈,愚公移山,每一学习者都会看完这本书的。