#include <stdio.h>
#include <stdlib.h>
#include <stack>
using namespace std;
struct Node{
int val;
struct Node *left;
struct Node *right;
};
//先序递归遍历
void fdfs(struct Node *root){
if(root == NULL){
return;
}
printf("%d ",root->val);
fdfs(root->left);
fdfs(root->right);
}
//中序递归遍历
void mdfs(struct Node *root){
if(root == NULL){
return ;
}
mdfs(root->left);
printf("%d ",root->val);
mdfs(root->right);
}
//后序递归遍历
void hdfs(struct Node *root){
if(root == NULL){
return;
}
hdfs(root->left);
mdfs(root->right);
printf("%d ",root->val);
}
//非递归前序遍历
void f(struct Node *root){
stack<struct Node*> st;
while(root!=NULL || !st.empty()){
while(root != NULL){
printf("%d ",root->val);
st.push(root);
root = root->left;
}
//左节点没有子节点则弹栈并寻找右节点
if(!st.empty()){
root = st.top();
st.pop();
root = root->right;
}
}
}
//非递归中序遍历
void m(struct Node *root){
stack<struct Node*> st;
while(root != NULL || !st.empty()){
while(root!=NULL){
st.push(root);
root = root->left;
}
if(!st.empty()){
root = st.top();
st.pop();
printf("%d ",root->val);
root = root->right;
}
}
}
//非递归后序遍历
void h(struct Node *root){
stack<struct Node*> st;
//每次遍历上一次访问的节点
struct Node *last = NULL;
while(root!=NULL || !st.empty()){
while(root!=NULL){
st.push(root);
root = root->left;
}
if(!st.empty()){
root = st.top();
st.pop();
if(root->right == NULL || root->right==last){
printf("%d ",root->val);
last = root;
root = NULL;
}
else{
st.push(root);
root = root->right;
}
}
}
}
二叉树的遍历
最新推荐文章于 2024-01-27 15:36:29 发布