突然晚上想到二叉树的三种遍历写法,老夫就装大一小朋友写一写二叉树的递归和非递归版的前、中、后序遍历。
1、二叉树定义
struct node{
char ch;
node* leftchild;
node* rightchild;
};
2、二叉树建立
按前序输入构建一棵二叉树,字符‘#’表示空子树
void createTree(node &T){
char str;
cin >> str;
if(str == '#'){
T = NULL;
}
else{
T = new node;
T->ch = str;
createTree(T->leftchild);
createTree(T0>rightchild);
}
}
3、二叉树的深度遍历
(1)前序遍历
递归版本:
void PreVisit(node* T){
if(T){
cout << T->ch << endl;
PreVisit(T->leftchild);
PreVisit(T->rightchild);
}
}
非递归版本:
void PreVisit(node* T){
if(T) return;
node* cur = T;
stack<node*> s;
s.push(cur);
while(!s.empty()){
cur = s.top();
cout << cur.ch;
s.pop();
if(cur->leftchild != NULL)
s.push(cur->leftchild);
if(cur->rightchild != NULL)
s.push(cur->rightchild);
}
}
(2)中序遍历
递归版本:
void PreVisit(node* T){
if(T){
PreVisit(T->leftchild);
cout << T->ch << endl;
PreVisit(T->rightchild);
}
}
非递归版本:
void MidVisit(node* T){
if(T==NULL)
return;
node* cur = T;
stack<node*> s;
s.push(cur);
while(!s.empty()){
while(s.top()->leftchild != NULL)
s.push(s.top()->leftchild);
while(!s.empty()){
node* cur = s.top();
cout << cur->ch;
s.pop();
if(s.rightchild != NULL){
s.push(s.rightchild);
break;
}
}
}
}
(3)后序遍历
递归版本:
void PreVisit(node* T){
if(T){
PreVisit(T->leftchild);
PreVisit(T->rightchild);
cout << T->ch << endl;
}
}
非递归版本:
void PostVisit(node* T){
if(T == NULL)
return;
stack<node*> s;
s.push(T);
node* lastpop = NULL;
while(!s.empty()){
while(s.top()->leftchild != NULL)
s.push(s.top()->leftchild;
while(!s.empty()){
if(lastpop == s.top()->rightchild || s.top()->rightchild == NULL){
cout << s.top()->ch<<endl;
lastpop = s.top();
s.pop();
}
else if(s.top()->rightchild != NULL){
s.push(s.top()->rightchild);
break;
}
}
}
}
4、二叉树层次遍历——用队列实现
void LevelVisit(node* T){
if(T == NULL)
return;
queue<node*> q;
q.push(T);
while(!q.empty()){
cout << q.front()->ch<<endl;
if(q.front()->leftchild != NULL)
q.push(q.front()->leftchild);
if(q.front()->rightchild != NULL)
q.push(q.front()->rightchild);
q.pop();
}
}