#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
//前序遍历-递归
void preorder(TreeNode *root,vector<int> &vec)
{
if(root!=NULL)
{
vec.push_back(root->val);
preorder(root->left,vec);
preorder(root->right,vec);
}
}
//前序遍历-非递归
void Preorder(TreeNode *root,vector<int> &vec)
{
if(root==NULL)
return;
stack<TreeNode*> s;
TreeNode *cur=root;
s.push(root);
while(!s.empty())
{
cur=s.top();
vec.push_back(cur->val);
s.pop();
if(cur->right!=NULL)
s.push(cur->right);
if(cur->left!=NULL)
s.push(cur->left);
}
}
//中序遍历-递归
void inorder(TreeNode *root,vector<int> &vec)
{
if(root!=NULL)
{
inorder(root->left,vec);
vec.push_back(root->val);
inorder(root->right,vec);
}
}
//中序遍历-非递归
void Inorder(TreeNode *root,vector<int> &vec)
{
if(root==NULL) return;
TreeNode *cur=root;
stack<TreeNode*> s;
while(cur!=NULL||!s.empty())
{
while(cur!=NULL)
{
s.push(cur);
cur=cur->left;
}
cur=s.top();
vec.push_back(cur->val);
s.pop();
cur=cur->right;
}
}
//后序遍历-递归
void postorder(TreeNode *root,vector<int> &vec)
{
if(root!=NULL)
{
postorder(root->left,vec);
postorder(root->right,vec);
vec.push_back(root->val);
}
}
//后序遍历-非递归1
void Postorder(TreeNode *root,vector<int> &vec)
{
if(root==NULL) return;
stack<TreeNode*> s;
TreeNode *cur=root;
s.push(root);
while(!s.empty())
{
cur=s.top();
vec.push_back(cur->val);
s.pop();
if(cur->left!=NULL)
s.push(cur->left);
if(cur->right!=NULL)
s.push(cur->right);
}
reverse(vec.begin(),vec.end());
}
//后序遍历-非递归2
void Postorder2(TreeNode *root,vector<int> &vec)
{
if(root==NULL) return;
stack<TreeNode*> s;
s.push(root);
TreeNode *cur=root;
TreeNode *pre=NULL;
while(!s.empty())
{
cur=s.top();
if((cur->left==NULL && cur->right==NULL) || ((pre!=NULL)&&(cur->left==pre || cur->right==pre)))
{
vec.push_back(cur->val);
s.pop();
pre=cur;
}
else
{
if(cur->right!=NULL)
s.push(cur->right);
if(cur->left!=NULL)
s.push(cur->left);
}
}
}
int main()
{
vector<int> result;
TreeNode *test=new TreeNode(1);
test->left=new TreeNode(2);
test->right=new TreeNode(3);
preorder(test,result);
for(int i=0;i<result.size();i++)
cout<<result[i]<<" ";
cout<<endl;
return 0;
}
前序中序后序遍历总结
最新推荐文章于 2025-07-10 17:15:15 发布