#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
struct BNode
{
int data;
BNode *lchild, *rchild;
};
//创建二叉树
BNode* creatBinTree(vector<int> vec);
void insert(BNode* &root, int x);
//先序遍历
void preOrder1(BNode*);
void preOrder2(BNode*);
//中序遍历
void inOrder1(BNode*);
void inOrder2(BNode*);
//后序遍历
void postOrder1(BNode*);
void postOrder2(BNode*);
int main()
{
vector<int> vec = { 0, 8, 10, 34, 88, 2, 4, 6, 1, 990, 1000, 99, 20, 19, 15, 79, 38, 666 };
BNode* root = creatBinTree(vec);
cout << "*************递归先序遍历*************" << endl;
preOrder1(root);
cout << "*************非递归先序遍历*************" << endl;
preOrder2(root);
cout << "*************递归中序遍历*************" << endl;
inOrder1(root);
cout << "*************非递归中序遍历*************" << endl;
inOrder2(root);
cout << "*************递归后序遍历*************" << endl;
postOrder1(root);
cout << "*************非递归后序遍历*************" << endl;
postOrder2(root);
system("pause");
return 0;
}
BNode* creatBinTree(vector<int> vec)
{
BNode* root = NULL;
for (auto a : vec)
{
insert(root, a);
}
return root;
}
void insert(BNode* &root, int x)
{
if (root == NULL)
{
root = new BNode;
root->data = x;
root->lchild = root->rchild = NULL;
}
else
{
if (x < root->data) insert(root->lchild, x);
else insert(root->rchild, x);
}
}
//先序遍历
void preOrder1(BNode* root)
{
if (root == NULL) return;
cout << root->data << endl;
preOrder1(root->lchild);
preOrder1(root->rchild);
}
void preOrder2(BNode* root)
{
stack<BNode*> sta;
if (root == NULL) return;
BNode* now = root;//记录当前要访问的节点
while (true)
{
cout << now->data << endl;
if (now->rchild != NULL) sta.push(now->rchild);//后进先出,先访问左子树再访问右子树
if (now->lchild != NULL) sta.push(now->lchild);
if (sta.empty()) break;
now = sta.top();
sta.pop();
}
}
//中序遍历
void inOrder1(BNode* root)
{
if (root == NULL) return;
inOrder1(root->lchild);
cout << root->data << endl;
inOrder1(root->rchild);
}
void inOrder2(BNode* root)
{
stack<BNode*> sta;
if (root == NULL) return;
//BNode* now = root->lchild;//记录当前要访问的节点
while (true)
{
if (root != NULL)
{
sta.push(root);
root = root->lchild;
}
else if (!sta.empty())
{
root = sta.top();
sta.pop();
cout << root->data << endl;
root = root->rchild;
}
else break;
}
}
//后序遍历
void postOrder1(BNode* root)
{
if (root == NULL) return;
postOrder1(root->lchild);
postOrder1(root->rchild);
cout << root->data << endl;
}
void postOrder2(BNode* root)
{
stack<BNode*> sta, printSta;
if (root == NULL) return;
sta.push(root);
while (!sta.empty())
{
root = sta.top();
sta.pop();
printSta.push(root);
if (root->lchild != NULL) sta.push(root->lchild);
if (root->rchild != NULL) sta.push(root->rchild);
}
while (!printSta.empty())
{
root = printSta.top();
printSta.pop();
cout << root->data << endl;
}
}
二叉树的三种非递归遍历
猜你喜欢
转载自blog.csdn.net/wddpfx/article/details/82015337
今日推荐
周排行