前言
二叉树的递归遍历在我上一篇“二叉树及其三种序的递归遍历”里有。其中用到的“BinaryTree”也在链接文章的“二叉树的创建”里。大一计算机的自学总结:二叉树及其三种序的递归遍历
而非递归遍历是借助栈的特性,会更难更复杂。TvT......
一、先序遍历
#include<bits/stdc++.h>
#include"BinaryTree.h"
using namespace std;
//非递归先序遍历二叉树
void preOrder(TreeNode* head)
{
if(head!=NULL)
{
stack<TreeNode*>s;
s.push(head);
while(!s.empty())
{
head=s.top();
cout<<head->value<<" ";
s.pop();
if(head->right!=NULL)
{
s.push(head->right);
}
if(head->left!=NULL)
{
s.push(head->left);
}
}
}
}
int main()
{
TreeNode* head=NULL;
addTree(head);
//非递归先序遍历二叉树
cout<<"preorder:"<<endl;
preOrder(head);
return 0;
}