binary tree breadth first traversal in c++

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. 

转载于:https://www.cnblogs.com/RuiYan/p/4088615.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值