20170816_二叉树的建立+前序遍历+中序遍历+后序遍历+层序遍历

来源:互联网 发布:淘宝店铺可以转吗 编辑:程序博客网 时间:2024/06/03 11:16

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、前序遍历二叉树:借助栈stackvoid 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、中序遍历二叉树:借助栈stackvoid 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、层序遍历二叉树:借助队列queuevoid 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 -1CreatBiTree(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层序遍历二叉树完成.请按任意键继续. . .*/






阅读全文
0 0
原创粉丝点击