#include <iostream> #include <vector> #include <deque> #include <map> #include <set> #include <string> #include <cstring> #include <cstdlib> using namespace std; typedef struct BinTree{ int data; struct BinTree *left; struct BinTree *right; }BinTree; /* 前序遍历 */ void PreOrder(BinTree *root){ if(root == NULL) return; BinTree *p = root; cout<<p->data<<endl;; PreOrder(p->left); PreOrder(p->right); } /* 中序遍历 */ void InOrder(BinTree *root){ if(root == NULL) return; BinTree *p = root; InOrder(p->left); cout<<p->data<<endl;; InOrder(p->right); } /* 后序遍历 */ void PostOrder(BinTree *root){ if(root==NULL) return; BinTree *p = root; PostOrder(p->left); PostOrder(p->right); cout<<p->data<<endl;; } /* 按照层序遍历方法遍历二叉树,使用一个队列来辅助 */ void BreadthFirst(BinTree *root){ if(root == NULL) return; deque<BinTree *> q; q.push_back(root); BinTree *p; while(!q.empty()){ p = q.front(); q.pop_front(); cout<<p->data; if(p->left) q.push_back(p->left); if(p->right) q.push_back(p->right); } } /* 按照前序遍历的方式构造二叉树 */ void CreateBinTree(BinTree **root){ int data; cin>>data; if(data == 0){ *root = NULL; }else{ *root = (BinTree *)malloc(sizeof(BinTree)); if(!*root) return; (*root)->data = data; CreateBinTree(&(*root)->left); CreateBinTree(&(*root)->right); } } int main(){ BinTree *root; CreateBinTree(&root); BreadthFirst(root); return 0; }