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.