二叉树的建立,输出,查找,c/c++描述(下)程序篇

  本程序来自课本例题,主要包括根据一个字符串数组,即二叉树的逗号表达式,建立二叉树,由函数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;
}

  测试结果如下:
在这里插入图片描述
在这里插入图片描述

谢谢阅读。数据结构很难。日积月累,坚持不懈,愚公移山,每一学习者都会看完这本书的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值