Tree.h
#pragma once
#include<queue>
#include <iostream>
#include<cstring>
using namespace std;
typedef struct node {
char val;
node* lchild;
node* rchild;
} BTNode;
class BTree {
private:
BTNode* creatTree();
BTNode* root;
void Release(BTNode* bt);
void PreOrder(BTNode* bt);
void InOrder(BTNode* bt);
void PostOrder(BTNode* bt);
int LeafCount(BTNode* bt);
int PointCount(BTNode* bt);
int Deepth(BTNode* bt);
public:
BTree() {
root= creatTree();
}
void PreOrder() {
PreOrder(root);
cout << endl;
}
void InOrder() {
InOrder(root);
cout << endl;
}
void PostOrder() {
PostOrder(root);
cout << endl;
}
void LevelOrder();
void LeafCount() {
cout << LeafCount(root);
cout << endl;
}
void PointCount() {
cout << PointCount(root);
cout << endl;
}
void Deepth() {
cout<<Deepth(root);
cout << endl;
}
~BTree() {
Release(root);
}
};
Tree.cpp
#include "Tree.h"
#include <iostream>
using namespace std;
BTNode* BTree::creatTree()
{
BTNode* bt ;
char ch;
cin >> ch;
if (ch == '#') {
bt = nullptr;
}
else {
bt = new BTNode;
bt->val = ch;
bt->lchild= creatTree();
bt->rchild=creatTree();
}
return bt;
}
void BTree::Release(BTNode* bt)
{
if (bt == nullptr)
return;
else {
Release(bt->lchild);
Release(bt->rchild);
delete bt;
}
}
void BTree::PreOrder(BTNode* bt)
{
if (!bt)
return;
else {
cout << bt->val;
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
void BTree::InOrder(BTNode* bt)
{
if (!bt)
return;
else {
InOrder(bt->lchild);
cout << bt->val;
InOrder(bt->rchild);
}
}
void BTree::PostOrder(BTNode* bt)
{
if (!bt)
return;
else {
PostOrder(bt->lchild);
PostOrder(bt->rchild);
cout << bt->val;
}
}
int BTree::LeafCount(BTNode* bt)
{
if (bt == nullptr)
return 0;
if (bt->lchild == nullptr && bt->rchild == nullptr)
return 1;
else
return LeafCount(bt->lchild) + LeafCount(bt->rchild);
}
int BTree::PointCount(BTNode* bt)
{
if (bt == nullptr)
return 0;
return PointCount(bt->lchild) + PointCount(bt->rchild) + 1;
}
int BTree::Deepth(BTNode* bt)
{ if(!bt)
return 0;
else {
int m = Deepth(bt->lchild);
int n = Deepth(bt->rchild);
if (m > n)
{
return m + 1;
}
else
{
return n + 1;
}
}
}
void BTree::LevelOrder()
{
BTNode* temp;
queue<BTNode*> st;
st.push(root);
while (!st.empty()) {
temp = st.front();
cout << temp->val;
st.pop();
if (temp->lchild != nullptr)
st.push(temp->lchild);
if (temp->rchild != nullptr)
st.push(temp->rchild);
}
cout << endl;
}
testTree.cpp
#include"Tree.h"
#include<iostream>
#include<vector>
using namespace std;
int main() {
cout << "请输入二叉树序列" << endl;
BTree T;
cout << "前序 ";
T.PreOrder();
cout << "中序 " ;
T.InOrder();
cout <<"后序 ";
T.PostOrder();
cout <<"层序 " ;
T.LevelOrder();
cout <<"叶节点总数 " ;
T.LeafCount();
cout <<"节点总数 ";
T.PointCount();
cout << "节点深度 ";
T.Deepth();
return 0;
}
结果