#include <iostream>
#include <stack>
#include <vector>
using namespace std;
/*
*输入样例 1 2 -1 -1 3 -1 -1
*输入样例 1 2 3 -1 -1 4 -1 -1 5 6 -1 -1 7 -1 -1
*输入样例 1 2 -1 3 -1 -1 4 5 -1 -1 -1
*/
struct Node {
Node* left;
Node* right;
int data;
Node(int x) :data(x), left(nullptr), right(nullptr) {};
};
void createBtiTree(Node* &root)
{
int data;
cin >> data;
if (data == -1) {
root = nullptr;
return;
}
else {
root = new Node(data);
createBtiTree(root->left);
createBtiTree(root->right);
}
}
void visit(Node *T)
{
if (T->data != -1)
cout << T->data << " ";
}
//前序递归遍历
void preOrderRecur(Node* root)
{
if (root == nullptr)
return;
else
{
visit(root);
preOrderRecur(root->left);
preOrderRecur(root->right);
}
}
//中序递归遍历
void inOrderRecur(Node* root)
{
if (root == nullptr)
return;
else
{
inOrderRecur(root->left);
visit(root);
inOrderRecur(root->right);
}
}
//后序递归遍历
void postOrder(Node * root)
{
if (root != nullptr)
{
postOrder(root->left);
postOrder(root->right);
visit(root);
}
}
//非递归前序遍历
void preOrderF(Node * root)
{
if (root == nullptr)
return;
stack<Node *> s;
s.push(root);
Node *p = nullptr;
while (!s.empty())
{
p = s.top();
s.pop();
visit(p);
if (p->right)
s.push(p->right);
if (p->left)
s.push(p->left);
}
}
void preOrderF_2(Node *root)
{
if (root == nullptr)
return;
stack<Node *> s;
Node *p = root;
while(p || !s.empty())
{
if (p)
{
visit(p);
if (p->right)
s.push(p->right);
p = p->left;
}
else
{
p = s.top();
s.pop();
}
}
}
//非递归中序遍历
void inOrderF(Node * root)
{
if (root == nullptr)
return;
stack<Node *> s;
Node *p = root;
while (p || !s.empty())
{
if (p)
{
s.push(p);
p = p->left;
}
else
{
p = s.top();
s.pop();
visit(p);
p = p->right;
}
}
}
//非递归后序遍历
void postOrderF(Node *root)
{
if (root == nullptr)
return;
stack<Node *> s1;
stack<Node *> s2;
Node *p = nullptr;
s1.push(root);
while (!s1.empty())
{
p = s1.top();
s1.pop();
s2.push(p);
if (p->left)
s1.push(p->left);
if (p->right)
s1.push(p->right);
}
while (!s2.empty())
{
p = s2.top();
visit(p);
s2.pop();
}
}
int main()
{
Node *root;
createBtiTree(root);
cout << "递归前序遍历" << endl;
preOrderRecur(root);
cout << endl;
cout << "------------------------"<<endl;
cout << "递归中序遍历" << endl;
inOrderRecur(root);
cout << endl;
cout << "------------------------" << endl;
cout << "递归后序遍历" << endl;
postOrder(root);
cout << endl;
cout << "------------------------" << endl;
cout << "非递归前序遍历" << endl;
preOrderF(root);
cout << endl;
cout << "------------------------" << endl;
cout << "非递归中序遍历" << endl;
inOrderF(root);
cout << endl;
cout << "------------------------" << endl;
cout << "非递归后序遍历" << endl;
postOrderF(root);
cout << endl;
cout << "------------------------" << endl;
system("pause");
return 0;
}
二叉树的递归和非递归方式的三种遍历
猜你喜欢
转载自blog.csdn.net/qq_25800311/article/details/80946646
今日推荐
周排行