码迷,mamicode.com
首页 > 编程语言 > 详细

binary tree breadth first traversal in c++

时间:2014-11-11 07:03:12      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   ar   sp   for   div   log   

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

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

 1 void BFS(TreeNode<T>* node){
 2    if(node == NULL) // if node is NULL, return
 3       return;
 4   else{
 5      std::list<TreeNode<T>* > current;
 6      current.push_back(node);
 7      while( current.size != 0){
 8         std::list<TreeNode<T>* > next_level;
 9         for(std::list<TreeNode<T>* >::iterator itr = current.beign();
10               itr != current.end(); ++itr){
11            if(node->left) next_level.push_back(node->left);
12            if(node->right) next_level.push_back(node->right);
13         }
14         current = next_level;
15     }  
16   }   
17 }

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

binary tree breadth first traversal in c++

标签:des   style   blog   color   ar   sp   for   div   log   

原文地址:http://www.cnblogs.com/RuiYan/p/4088615.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!