前序遍历二叉树
前序遍历二叉树的方式是 LVR 即左 - 根 - 右。
一般有递归和非递归两种方式,递归的方式就是先访问父结点,然后递归的访问左子树,再递归的访问右子树。
非递归在访问完父节点后先把右子树压栈,再把左子树压栈,然后栈非空的条件下弹栈访问,继续执行之前的动作,与递归前序的思想完全相同。
依旧是这棵老树:
/*------------
树的形状:
a
b c
d e f
--------------*/
代码如下:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
typedef struct node{
char val;
struct node* left;
struct node* right;
}TreeNode,*Tree;
//前序遍历(递归)
void preOrder(Tree& t){
if(t == NULL) return; //空树返回
cout<<t->val<<" "; //输出当前结点的值
//递归遍历左子树
preOrder(t->left);
//递归遍历右子树
preOrder(t->right);
}
//前序遍历(非递归)
void preOrderTraversal(Tree& t){
if(t == NULL) return; //空树返回
stack<TreeNode*> s; //创建一个TreeNode型的栈
s.push(t); //根结点入栈
while(!s.empty()){ //栈非空一直进行迭代
//弹栈一个结点,输出它的val
TreeNode* p = s.top(); //t是根指针无法移动,所以申请一个p指针来遍历整棵树
cout<<p->val<<" ";
s.pop();
//右子树非空先压栈
if(p->right != NULL)
s.push(p->right);
//左子树在右子树后面压栈,之后会比右子树先出栈
if(p->left != NULL)
s.push(p->left);
}
}
//构造树
void CreateTree(Tree& t){
char x;
cin>>x;
if(x == '#') t = NULL;
else{
t = new TreeNode;
t->val = x;
CreateTree(t->left);
CreateTree(t->right);
}
}
//层次遍历展示
void levelOrder(Tree& t) {
if(t == NULL) return;
queue<TreeNode*> q;
q.push(t);
while(!q.empty()){
int n = q.size();
for(int i = 0;i<n;i++){
TreeNode* s = q.front();
cout<<s->val<<" ";
q.pop();
if(s->left) q.push(s->left);
if(s->right) q.push(s->right);
}
cout<<endl;
}
}
int main(){
Tree t;
CreateTree(t);
/*
a b d # # e # # c f # # #
*/
levelOrder(t);
cout<<endl<<"递归:"<<endl;
preOrder(t);
cout<<endl<<"非递归:"<<endl;
preOrderTraversal(t);
}
运行结果:
前序镜像遍历二叉树
前序镜像遍历二叉树,顾名思义就是 RVL 即右 - 根 - 左。
实现方式把递归和非递归里的关于左子树和右子树的全部语句调换就可以了。
代码如下:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
typedef struct node{
char val;
struct node* left;
struct node* right;
}TreeNode,*Tree;
void preOrder(Tree& t){
if(t == NULL) return;
cout<<t->val<<" ";
preOrder(t->right);
preOrder(t->left);
}
void preOrderTraversal(Tree& t){
if(t == NULL) return;
stack<TreeNode*> s;
s.push(t);
while(!s.empty()){
TreeNode* p = s.top();
cout<<p->val<<" ";
s.pop();
if(p->left != NULL)
s.push(p->left);
if(p->right != NULL)
s.push(p->right);
}
}
void CreateTree(Tree& t){
char x;
cin>>x;
if(x == '#') t = NULL;
else{
t = new TreeNode;
t->val = x;
CreateTree(t->left);
CreateTree(t->right);
}
}
void levelOrder(Tree& t) {
if(t == NULL) return;
queue<TreeNode*> q;
q.push(t);
while(!q.empty()){
int n = q.size();
for(int i = 0;i<n;i++){
TreeNode* s = q.front();
cout<<s->val<<" ";
q.pop();
if(s->left) q.push(s->left);
if(s->right) q.push(s->right);
}
cout<<endl;
}
}
int main(){
Tree t;
CreateTree(t);
/*
a b d # # e # # c f # # #
*/
levelOrder(t);
cout<<endl<<"递归:"<<endl;
preOrder(t);
cout<<endl<<"非递归:"<<endl;
preOrderTraversal(t);
}
结果如下: