-
二叉链表的C语言描述
-
基本运算的算法——建立二叉链表、先序遍历二叉树、中序遍历二叉树、后序遍历二叉树、后序遍历求二叉树深度
#include<iostream>
#include<cstdio>
using namespace std;
class Tree
{
private:
struct Node
{
char data;
Node * lchild;
Node * rchild;
Node()
{
lchild = NULL;
rchild = NULL;
}
Node(char a)
{
data = a;
lchild = NULL;
rchild = NULL;
}
};
void creatTree(Node* &head)
{
char a;
cin>>a;
if(a == '#')
{
head->lchild = head->rchild = NULL;
head = NULL;
}
else
{
head->data = a;
head->lchild = new Node();
head->rchild = new Node();
creatTree(head->lchild);
creatTree(head->rchild);
}
}
void NLR(Node *head)
{
if(head)
{
cout<<head->data;
NLR(head->lchild);
NLR(head->rchild);
}
else cout<<"#";
}
void LNR(Node *head)
{
if(head)
{
LNR(head->lchild);
cout<<head->data;
LNR(head->rchild);
}
else cout<<"#";
}
void LRN(Node * head)
{
if(head)
{
LRN(head->lchild);
LRN(head->rchild);
cout<<head->data;
}
else cout<<"#";
}
public:
Node * head;
Node * cur;
Tree() {}
Tree(char a)
{
Node * tem = new Node(a);
head = tem;
cur = tem;
}
void creatTree()
{
head = new Node();
creatTree(head);
}
void NLR()
{
if(head)
NLR(head);
else cout<<"#";
}
void LNR()
{
if(head)
LNR(head);
else cout<<"#";
}
void LRN()
{
if(head)
{
LRN(head);
}
else cout<<"#";
}
int BiTreeDeep(Node * head)
{
int dept = 0;
if(head)
{
int lchilddept = BiTreeDeep(head->lchild);
int rchilddept = BiTreeDeep(head->rchild);
dept = lchilddept >= rchilddept ? (lchilddept + 1) : (rchilddept + 1);
}
return dept;
}
};
int main()
{
Tree dusk;
dusk.creatTree();
int cnt = 0;
dusk.NLR();
cout<<endl;
dusk.LNR();
cout<<endl;
dusk.LRN();
cout<<endl;
cout<<dusk.BiTreeDeep(dusk.head);
}