Title Description:
Each node of the two-fork tree is printed from top to bottom, and the same-level node prints from left to right.
Ideas:
The root node is queued, then the loop determines whether the queue is empty, does not empty the queue, and then determines whether the node of the queue contains the left and right nodes, and some words, the left and right sub-nodes into the queue, until the queue is empty
The implementation code is as follows:
#include <iostream>#include<queue>using namespacestd;structTreeNode {Chardata; TreeNode*Lchild; TreeNode*rchild;}; //First Order Create two-fork treeTreeNode *init () {Chardata; cout<<"Please Inpur a number: (#代表NULL)"<<Endl; CIN>>data; if(data=='#') returnNULL; TreeNode*head=NewTreeNode; Head->data=data; Head->lchild=init (); Head->rchild=init (); returnhead;}//print binary tree by levelvoidPrint (TreeNode *head) {Queue<treenode *>Myque; if(head) {Myque.push (head); } while(!Myque.empty ()) { //get data for the queue header and printTreeNode *temp=Myque.front (); cout<<temp->data<<" "; Myque.pop (); if(temp->lchild) Myque.push (temp-lchild); if(temp->rchild) Myque.push (temp-rchild);} }
Test the code and run the results:
int Main () { *head=init (); Print (head); return 0 ;}
Traverse a binary tree by hierarchy