Binary tree breadth First traversal in C + +

Source: Internet
Author: User

BFS is faster-find shortest path from root to leaf node of a tree. But the tradeoff are to use more memory.

The basic trategy is to maintain a list-to-hold nodes of each level.

1 voidBFS (treenode<t>*node) {2    if(node = =null)//If node is null, return3       return;4   Else{5std::list<treenode<t>* >Current ;6 current.push_back (node);7       while(Current.size! =0){8std::list<treenode<t>* >Next_level;9          for(std::list<treenode<t>* >::iterator ITR =current.beign ();TenITR! = Current.end (); ++ITR) { One            if(node->left) Next_level.push_back (node->Left ); A            if(node->right) Next_level.push_back (node->Right ); -         } -Current =Next_level; the     }   -   }    -}

You could use iterator to traverse the current list to print out the values as well.

Binary tree breadth First traversal in C + +

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.