二叉树的基本操作主要是输入的时候,对于一个叶子节点,它同样也是根节点,所以我们要输入两个空字符,代码中是以#代替的。
还有就是广义表建立二叉树的时候,我们要让每次循环的P指针先指向处理后的根节点,然后进而让根节点入栈,此时用栈模拟先序建立,因为入栈出栈的过程就像dfs。
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <stack>
using namespace std;
typedef char ElementType;
typedef struct BiTreeNode {
ElementType data;
struct BiTreeNode *Lchild;
struct BiTreeNode *Rchild;
}BiTreeNode,*BiTree;
BiTreeNode Tree;//创建根节点
//先序建立二叉树
void CreateBiTree(BiTree &T)
{
char data;
data=getchar();
if (data=='#') {
T=NULL;
return ;
}
else {
T=new BiTreeNode;
T->data=data;
CreateBiTree(T->Lchild);
CreateBiTree(T->Rchild);
}
}
void GenListCreateBiTree(BiTree &T)
{
stack<BiTree> Stack;
BiTree P=NULL;
int k=0;
char ch=getchar();
//根的处理
if (ch!='#') {
T->data=ch;
T->Lchild=NULL;
T->Rchild=NULL;
P=T;
}
while ((ch=getchar())!='#') {
switch (ch) {
case '(':
Stack.push(P);//首先让根入栈
k=1;
break;
case ',':
k=2;
break;
case ')':
Stack.pop();
break;
default:
P=new BiTreeNode;
P->data=ch;
P->Lchild=NULL;
P->Rchild=NULL;
if (k==1) {
Stack.top()->Lchild=P;
}
else {
Stack.top()->Rchild=P;
}
}
}
}
void GenListPrintTree(BiTree &T)
{
if(T) {
cout<<T->data;
if (T->Lchild||T->Rchild) {
cout<<"(";
GenListPrintTree(T->Lchild);
cout<<",";
if (T->Rchild) {
GenListPrintTree(T->Rchild);
}
cout<<")";
}
}
}
void PreOrderTraverse(BiTree T)
{
if (T) {
cout<<T->data<<" ";
PreOrderTraverse(T->Lchild);
PreOrderTraverse(T->Rchild);
}
}
void InOrderTraverse(BiTree T)
{
if (T) {
InOrderTraverse(T->Lchild);
cout<<T->data<<" ";
InOrderTraverse(T->Rchild);
}
}
void PostOrderTraverse(BiTree T)
{
if (T) {
PostOrderTraverse(T->Lchild);
PostOrderTraverse(T->Rchild);
cout<<T->data<<" ";
}
}
int BiTreeDepth(BiTree &T)
{
if (T==NULL)
return 0;
if (T) {
int depthL=BiTreeDepth(T->Lchild);
int depthR=BiTreeDepth(T->Rchild);
return (depthL>depthR)?(depthL+1):(depthR+1);
}
}
int TwoDegreeCountBiTree(BiTree &T)
{
if (T==NULL) {
return 0;
}
int cnt=0;
if (T->Lchild&&T->Rchild) {
cnt++;
}
return cnt+TwoDegreeCountBiTree(T->Lchild)+TwoDegreeCountBiTree(T->Rchild);
}
void DestroyBiTree(BiTree &T)
{
if (T) {
DestroyBiTree(T->Lchild);
DestroyBiTree(T->Rchild);
delete T;
T=NULL;
}
}
int main()
{
BiTree address=&Tree;
cout<<"先序创建一棵二叉树(#为空):"<<endl;
CreateBiTree(address);
//GenListCreateBiTree(address); a(b(c,d),)#
cout<<"先序遍历:"<<endl;
PreOrderTraverse(address);
cout<<endl;
cout<<"中序遍历:"<<endl;
InOrderTraverse(address);
cout<<endl;
cout<<"后序遍历:"<<endl;
PostOrderTraverse(address);
cout<<endl;
cout<<"广义表先序输出二叉树:"<<endl;
GenListPrintTree(address);
cout<<endl;
cout<<"二叉树的深度为:"<<BiTreeDepth(address)<<endl;
cout<<"二叉树的二度节点个数为:"<<TwoDegreeCountBiTree(address)<<endl;
cout<<"二叉树的叶子节点个数为:"<<1+TwoDegreeCountBiTree(address)<<endl;
cout<<"二叉树已销毁"<<endl;
return 0;
}
/*
Bitree
-+a##*b##-c##d##/e##f##
*/