#include<iostream> #include<vector> using namespace std; const int Max=30; class Node { public: Node(int d):data(d),left(NULL),right(NULL){} int data; Node *left; Node *right; }; template<class T> class queue { public: queue(int i=Max):front(0),rear(0){Q=new T[Max];} void EnQueue(Node *p){Q[rear++] = p;} T DeQueue(){return Q[front++];} int front; int rear; T *Q; }; int PrintNodeAtLevel(Node *root,int level)//递归 { if(!root || level<0) return 0; if(level==0) { cout<<root->data<<" "; return 1; } PrintNodeAtLevel(root->left,level-1); PrintNodeAtLevel(root->right,level-1); } void PrintNode(Node *root) { for(int level=0; ;level++) { if(!PrintNodeAtLevel(root,level)) break; cout<<endl; } } void PrintNodeByLevel(Node *root)//非递归 { if(root==NULL) return; vector<Node *> vec; vec.push_back(root); int cur=0; int last=1; while(cur<vec.size()) { last=vec.size(); while(cur<last) { cout<<vec[cur]->data<<" "; if(vec[cur]->left) vec.push_back(vec[cur]->left); if(vec[cur]->right) vec.push_back(vec[cur]->right); cur++; } cout<<endl; } } void PrintNodeByBFS(Node *root) //BFS { if(root==NULL) return; queue<Node *> que; que.EnQueue(root); Node *q; while(que.front<que.rear) { int last=que.rear; while(que.front<last) { q=que.DeQueue(); cout<<q->data<<" "; if(q->left) que.EnQueue(q->left); if(q->right) que.EnQueue(q->right); } cout<<endl; } } //扩展问题 /* *依然是按层遍历二叉树,只是要求从下往上访问,并且每一层中结点的访问顺序为从右向左 *分析:只要层与层之间加入哑元素(NULL),然后逆序输出队列Q即可 */ void PrintNodeDown2UpRight2Left(Node *root) { if(root==NULL) return; queue<Node *> que; que.EnQueue(root); que.EnQueue(NULL); Node *q; while(que.front<que.rear-1) { int last=que.rear-1; while(que.front<last) { q=que.DeQueue(); if(q->left!=NULL) que.EnQueue(q->left); if(q->right!=NULL) que.EnQueue(q->right); } que.EnQueue(NULL);//如果左右子树为空又多加入一个NULL que.front=last+1; } for(int i=que.rear-3;0<=i;i--)//逆序打印 { if(que.Q[i]!=NULL) cout<<que.Q[i]->data<<" "; else cout<<endl; } cout<<endl;//只是为了排版 } int main() { Node *p1 = new Node(1); Node *p2 = new Node(2); Node *p3 = new Node(3); Node *p4 = new Node(4); Node *p5 = new Node(5); Node *p6 = new Node(6); Node *p7 = new Node(7); Node *p8 = new Node(8); p1->left = p2; p1->right = p3; p2->left = p4; p2->right = p5; p3->right = p6; p5->left = p7; p5->right = p8; Node *root = p1; //PrintNode(root); //PrintNodeByLevel(root); //PrintNodeByBFS(root); PrintNodeDown2UpRight2Left(root); return 0; }