#include <iostream>
extern "C"{
#include <stdio.h>
#include <stdlib.h>
}
using namespace std;
typedef struct BinTreeNode{
char cData;
BinTreeNode* lNode;
BinTreeNode* rNode;
}BinTreeNode;
char dataBuf[] = "ABDH#K###E##CFI###G#J##";
int index2 = 0;//注意此处全局变量不能使用index,index被库定义掉了
void createBinTree(BinTreeNode*& node)
{
char data = dataBuf[index2++];
if(data == '#')
return;
node = (BinTreeNode*)malloc(sizeof(BinTreeNode));
if(node == NULL)
return;
node->cData = data;
node->lNode = NULL;
node->rNode = NULL;
createBinTree(node->lNode);
createBinTree(node->rNode);
}
void createBinTree2(BinTreeNode*& node)
{
char data;
cout << "input node value:";
cin >> data;
if(data == '0'){
node = NULL;
return;
}
node = (BinTreeNode*)malloc(sizeof(BinTreeNode));
if(node == NULL){
return;
}
node->cData = data;
createBinTree2(node->lNode);//先序创建二叉树
createBinTree2(node->rNode);
}
int treeDepth(BinTreeNode* node)
{
int leftDepth,rightDepth;
if(node == NULL){
return 0;
}
else{
leftDepth = treeDepth(node->lNode);
rightDepth = treeDepth(node->rNode);
}
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
//横向打印树结构
void printBinTree(BinTreeNode* node,int depth)
{
int iTemp = depth;
if(node == NULL){
return;
}
printBinTree(node->rNode,depth+1);
while(--iTemp){
cout << " ";
}
cout << node->cData << endl;
printBinTree(node->lNode,depth+1);
}
bool findData(BinTreeNode* node,char data)
{
if(node == NULL)
return false;
if(node->cData == data){
cout << "find the data " << data << endl;
return true;
}
else{
bool res = findData(node->lNode,data);
if(res){
return true;
}
else{
res = findData(node->rNode,data);
return res;
}
}
}
int main(int argc,char* argv[])
{
BinTreeNode* node = NULL;
createBinTree(node);
printBinTree(node,1);
cout << "########################" << endl;
int depth = treeDepth(node);
cout << "the tree depth:" << depth << endl;
char data;
cin >> data;
bool res = findData(node,data);
cout << (res?"found":"not found")<< endl;
return 0;
}
二叉树
最新推荐文章于 2022-05-01 12:47:37 发布