1、树的顺序存储只等存储完全二叉树。
2、二叉树的遍历
递归形式
重点:每次递归可以分为3个子操作,能用递归的形式完成,递归结束的终点是T为叶节点,即左右节点是NULL。
#include<bits/stdc++.h>
using namespace std;
typedef struct TNode{
int data;
struct TNode* Left;
struct TNode* Right;
}*Tree;
//先序遍历
void Preprint(Tree T)
{
if(T)
{
printf("%d ",T->data);
Preprint(T->Left);
Preprint(T->Right);
}
}
//中序遍历
void Inorderprint(Tree T)
{
if(T)
{
Inorderprint(T->Left);
printf("%d ",T->data);
Inorderprint(T->Right);
}
}
//后序遍历
void Laterprint(Tree T)
{
if(T)
{
Laterprint(T->Left);
Laterprint(T->Right);
printf("%d ",T->data);
}
}
int main(void)
{
}
非递归
#include<bits/stdc++.h>
using namespace std;
typedef struct TNode{
int data;
struct TNode* Left;
struct TNode* Right;
}*Tree;
//中序遍历
void InorderPrint(Tree T)
{
Tree p=T;
Tree q=new struct TNode;
stack <Tree> s;
s.push(p);
while(!s.empty()||p)
{
if(p)
{
s.push(p);
p=p->Left;
}
else
{
q=s.top();
cout<<q->data<<endl;
s.pop();
p=q->Left;
}
}
}
//先序遍历
void PrePrint(Tree T)
{
Tree p=new struct TNode;
stack <Tree> s;
s.push(T);
while(!s.empty())
{
p=s.top();
s.pop();
printf("%d ",p->data);
if(p->Left)
s.push(p->Left);
if(p->Right)
s.push(p->Right);
}
}
//后序遍历
void LaterPrint(Tree T)
{
if(T==NULL) return ;
Tree p=new struct TNode;
vector <int> st;
stack <Tree> s;
s.push(p);
while(!s.empty())
{
p=s.top();
s.pop();
st.insert(st.begin(),p->data);
if(p->Left) s.push(p->Left);
if(p->Right) s.push(p->Right);
}
for(int i=0;i<st.size();i++)
cout<<st[i]<<endl;
}
int main(void)
{
}
二叉树遍历的应用
#include<bits/stdc++.h>
using namespace std;
typedef struct TNode{
char data;
struct TNode* Left;
struct TNode* Right;
}Tree;
//先序遍历建立二叉树
void Creat(Tree T)
{
char ch;
cin>>ch;
if(ch=='#') T=NULL;
else
{
T= new struct TNode;
T->data=ch;
Creat(T->Left);
Creat(T->Right);
}
}
//复制二叉树
void Copy(Tree T,Tree &C)
{
if(T==NULL)
{
C=NULL;
return ;
}
else
{
C=new struct TNode;
C->data=ch;
Copy(T->Left,C->Left);
Copy(T->Right,C->Right);
}
}
//深度计算
int m,n;
int Depth(Tree T)
{
if(T==NULL) return 0;
else{
m=Depth(T->Left);
n=Depth(T->Right);
return max(m,n)+1;
}
}
//节点统计
int Cnt(Tree T)
{
if(T==NULL) return 0;
else return Cnt(T->Left)+Cnt(T->Right)+1;
}
3、线索二叉树
记录二叉树的前驱和后继的信息
#include<bits/stdc++.h>
using namespace std;
typedef struct BinTree{
int data;
struct BinTree* Left;
struct BinTree* Right;
int Ltag,Rtag;
}*BhTree;
BhTree pre=NULL;
void InThreading(BhTree p)
{
if(p)
{
InThreading(p->Left);
if(!p->Left)
{
p->Ltag=1;
p->Left=pre;
}
else p->Ltag=0;
if(!p->Right)
{
p->Rtag=1;
p->Right=p;
}
else p->Rtag=0;
InThreading(p->Right);
}
}
//中序遍历生成线索二叉树
void InorderThreading(BhTree BT,BhTree T)
{
BT=new struct BinTree;
BT->Ltag=0;
BT->Rtag=1;
BT->Left=BT;
if(!T)
{
BT->Right=BT;
}
else
{
BT->Left=T;
pre=BT;
InThreading(T);
pre->Right=BT;
pre->Rtag=1;
BT->Right=pre;
}
}
int main(void)
{
}