层次遍历二叉树。
大致算法:
采用一个队列q,先将二叉树根结点入队列,然后退队列,输出该结点;若它有左子树,便将左子树根结点入队列;若它有右子树,便将右子树根结点入队列,如此直到队列空为止。
采用队列的方式:
void HiberarchyRetriveATree(TreeNode root,void (* visit)(TreeNode))
{
queue<TreeNode> tree;
TreeNode tmp = NULL;
tree.push(root);
while (!tree.empty())
{
tmp = tree.front();
tree.pop();
(*visit)(tmp);
if (tmp->_l != NULL)
tree.push(tmp->_l);
if (tmp->_r != NULL)
tree.push(tmp->_r);
}
}
void Visit(TreeNode node)
{
cout<<node->_value<<" ";
}