20170816_二叉树的建立+前序遍历+中序遍历+后序遍历+层序遍历
/*二叉树的建立_前序_中序_后序_层序
*/
/*判断一颗二叉树是不是平衡二叉树?
*/
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
struct BiTreeNode
{
int val;
BiTreeNode *pLeft;
BiTreeNode *pRight;
BiTreeNode(int x):val(x),pLeft(nullptr),pRight(nullptr) {}
};
//创建二叉树
void CreatBiTree(BiTreeNode * &root)
{
int ch;
cin>>ch;
getchar();
if(ch == -1)
{
root=NULL;
}
else
{
root=new BiTreeNode(ch);
CreatBiTree(root->pLeft);
CreatBiTree(root->pRight);
}
}
//1、前序遍历二叉树:借助栈stack
void PreOrder(BiTreeNode *root)
{
if(root==nullptr)
return;
stack<BiTreeNode *> s;
while(root != nullptr || !s.empty())
{
while(root != nullptr)
{
cout<<root->val<<" ";
s.push(root);
root=root->pLeft;
}
if(!s.empty())
{
root=s.top();
s.pop();
root=root->pRight;
}
}
}
//2、中序遍历二叉树:借助栈stack
void Inorder(BiTreeNode *root)
{
if(root==nullptr)
return;
stack<BiTreeNode *> s;
while(root != nullptr || !s.empty())
{
while(root != nullptr)
{
s.push(root);
root=root->pLeft;
}
if(!s.empty())
{
root=s.top();
s.pop();
cout<<root->val<<" ";
root=root->pRight;
}
}
}
//3、后序遍历二叉树:递归遍历方法
void PostOrder(BiTreeNode *root)
{
if(root==nullptr)
return;
else
{
PostOrder(root->pLeft);
PostOrder(root->pRight);
cout<<root->val<<" ";
}
}
//4、层序遍历二叉树:借助队列queue
void LevelOredr(BiTreeNode *root)
{
if(root==nullptr)
return;
queue<BiTreeNode *> q;
BiTreeNode *top;
q.push(root);
while(!q.empty())
{
top=q.front();
cout<<top->val<<" ";
q.pop();
if(top->pLeft != nullptr)
q.push(top->pLeft);
if(top->pRight != nullptr)
q.push(top->pRight);
}
}
//*****************************************
int main()
{
BiTreeNode *root;
cout<<"依次输入二叉树的结点数据:"<<endl; // 10 20 -1 40 -1 -1 30 -1 -1
CreatBiTree(root);
cout<<"二叉树建立完成."<<endl;
cout<<"前序遍历二叉树."<<endl;
PreOrder(root);
cout<<endl;
cout<<"前序遍历二叉树完成."<<endl;
cout<<"中序遍历二叉树."<<endl;
Inorder(root);
cout<<endl;
cout<<"中序遍历二叉树完成."<<endl;
cout<<"后序遍历二叉树."<<endl;
PostOrder(root);
cout<<endl;
cout<<"后序遍历二叉树完成."<<endl;
cout<<"层序遍历二叉树."<<endl;
LevelOredr(root);
cout<<endl;
cout<<"层序遍历二叉树完成."<<endl;
system("pause");
return 0;
}
/*
依次输入二叉树的结点数据:
1 2 4 -1 7 -1 -1 -1 3 5 -1 -1 6 -1 -1
二叉树建立完成.
前序遍历二叉树.
1 2 4 7 3 5 6
前序遍历二叉树完成.
中序遍历二叉树.
4 7 2 1 5 3 6
中序遍历二叉树完成.
后序遍历二叉树.
7 4 2 5 6 3 1
后序遍历二叉树完成.
层序遍历二叉树.
1 2 3 4 5 6 7
层序遍历二叉树完成.
请按任意键继续. . .
*/