#include<iostream>
#include<stack>
#include<vector>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) { val = x; left = nullptr; right = nullptr; };
};
using namespace std;
//二叉树前序非递归遍历
void preOrder(TreeNode * root) {
stack<TreeNode*> s;
while (root !=nullptr || !s.empty())
{
while(root!=nullptr){
cout << " " << root->val;
s.push(root);
root = root->left;
}
if (!s.empty())
{
root = s.top();
s.pop();
root = root->right;
}
}
}
//非递归中序遍历
void inorder(TreeNode * root) {
stack<TreeNode *> s;
while (!s.empty() || root!=nullptr)
{
while(root !=nullptr){
s.push(root);
root = root->left;
}
if (!s.empty()) {
root = s.top();
cout << " " << root->val;
s.pop();
root= root->right;
}
}
}
//非递归后序遍历
void postOrder(TreeNode * root) {
stack<TreeNode *> s;
TreeNode *cur = root;
TreeNode *pre = nullptr;
while (cur!=nullptr || !s.empty())
{
while (cur !=nullptr)
{
s.push(cur);
cur = cur->left;
}
if(!s.empty()){
TreeNode* cur= s.top();
if (cur->right == nullptr || pre == cur->right) {
cout << " " << cur->val;
pre = cur;
cur = nullptr;
s.pop();
}else{
cur = cur->right;
while (cur)
{
s.push(cur);
cur = cur->left;
}
}
}
}
}
TreeNode* makeTree() {
TreeNode* root = nullptr;
root=new TreeNode(1);
TreeNode* node2 = new TreeNode(8);
TreeNode* node3 = new TreeNode(3);
TreeNode* node4 = new TreeNode(4);
TreeNode* node5 = new TreeNode(5);
TreeNode* node6 = new TreeNode(6);
root->left = node2; root->right = node5;
node2->left = node3; node2->right = node4;
node5->left = node6;
return root;
}
int main() {
TreeNode * root = makeTree();
cout << endl << "二叉树非递归前序遍历" << endl;
preOrder(root);
cout << endl << "二叉树非递归中序遍历" << endl;
inorder(root);
cout << endl << "二叉树非递归后序遍历" << endl;
postOrder(root);
return 0;
}
二叉树非递归遍历
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
下一篇:浅谈各种排序算法
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
二叉树遍历-递归与非递归遍历
二叉树的遍历原则先序遍历:①访问当前结点,②遍历左子树,③遍历右子树中序遍历:①遍历左子树,②访问当前结点,③
数据结构 二叉树 结点 子树 非递归 -
非递归二叉树遍历结点 子树 二叉树 数组 数据结构
-
二叉树遍历非递归java 二叉树遍历非递归算法Java
1.先(根)序遍历的递归定义:若二叉树非空,则依次执行如下操作:⑴ 访问根结点;⑵ 遍历左子树;⑶ 遍历右子树。
二叉树遍历非递归java System Stack 子树