先中后序遍历的递归实现和非递归实现+层次遍历。
先中后序遍历
先序遍历
递归
//递归先序遍历
void pre_traverse(BTree pTree){
if(pTree){
printf("%c",pTree->data);
if(pTree->pLchild)
pre_traverse(pTree->pLchild);
if(pTree->pRchild)
pre_traverse(pTree->pRchild);
}
}
非递归
//非递归先序遍历
void pre_traverse(BTree pTree){
stack<BTree> sta; //创建一个空栈
BTree ptr=pTree; //指向当前访问节点的指针
//直到当前节点ptr为NULL且栈为空时,循环结束
while(!ptr||!sta.empty()){
//从根节点开始输出当前节点并将其入栈
//同时置其左孩子为当前节点,直至其没有左孩子及当前节点为NULL
cout<<ptr->data;
sta.push(ptr);
ptr=ptr->pLchild;
//如果当前节点ptr为NULL且栈不空,则将栈顶节点出栈
//同时置其右孩子为当前节点,循环判断,直至ptr不为空
while(!ptr&&!sta.empty()){
ptr=sta.top();
sta.pop();
ptr=ptr->pRchild;
}
}
}
中序遍历
递归
//递归中序遍历
void in_traverse(BTree pTree){
if(pTree){
if(pTree->pLchild)
in_traverse(pTree->pLchild);
printf("%c",pTree->data);
if(pTree->pRchild)
in_traverse(pTree->pRchild);
}
}
非递归
//非递归中序遍历
void in_traverse(BTree pTree){
stack<BTree> sta;
BTree ptr=pTree;
while(!ptr||!sta.empty()){
if(ptr->pLchild){
sta.push(ptr);
ptr=ptr->pLchild;
}
else{
cout<<ptr->data;
ptr=ptr->pRchild;
while(!ptr&&!sta.empty()){
ptr=sta.top();
cout<<ptr->data;
sta.pop();
ptr=ptr->pRchild;
}
}
}
}
后序遍历
递归
//递归后序遍历
void post_traverse(BTree pTree){
if(pTree){
if(pTree->pLchild)
in_traverse(pTree->pLchild);
if(pTree->pRchild)
in_traverse(pTree->pRchild);
print("%c",pTree->data);
}
}
非递归
//非递归后序遍历
void post_traverse(BTree pTree){
stack<BTree> sta;
BTree ptr=pTree;
BTree ptr_back=NULL; //指向上一各访问的节点的指针
sta.push(pTree);
while(!sta.empty()){
ptr=sta.top();
if((ptr->pLchild==NULL&&ptr->pRchild==NULL)||(ptr_back!=NULL&&(ptr->pLchild==ptr_back||ptr->pRchild==ptr_back))){
cout<<ptr->data;
sta.pop();
ptr_back=ptr;
}
else{
if(ptr->pRchild!=NULL) sta.push(ptr->pRchild);
if(ptr->pLchild!=NULL) sta.push(ptr->pLchild);
}
}
}
层次遍历
#include <iostream>
#include <queue>
using namespace std;
struct BinaryTree {
int val;
BinaryTree *left;
BinaryTree *right;
BinaryTree(int value)
: val(value), left(nullptr), right(nullptr) { }
};
void levelOrder(BinaryTree *root) {
if (root == nullptr)
return;
queue<BinaryTree*> que;
que.push(root);
while (!que.empty()) {
BinaryTree *front = que.front();
cout << front->val << " ";
que.pop();
if (front->left != nullptr)
que.push(front->left);
if (front->right != nullptr)
que.push(front->right);
}
}
已知二叉树的某两个遍历,求第三个遍历的问题参见另一篇博文。
二叉树已知两个遍历,求另一个遍历