Traverse a binary tree by hierarchy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.