前序中序后序遍历总结

本文深入探讨了二叉树的前序、中序和后序遍历算法,包括递归和非递归实现方式。通过实例代码展示了如何使用C++进行二叉树节点的创建,并实现了各种遍历方法,帮助读者理解不同遍历方式的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值