面试题23:从上往下打印二叉树

题目描述

从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。二叉树结点的定义如下:

题目分析

剑指Offer(纪念版)P137

代码实现

层序遍历

void PrintFromTopToBottom(BinaryTreeNode* pRoot)
{
    if(pRoot == NULL)
        return;

    std::deque<BinaryTreeNode *> dequeTreeNode;

    dequeTreeNode.push_back(pRoot);

    while(dequeTreeNode.size())
    {
        BinaryTreeNode *pNode = dequeTreeNode.front();
        dequeTreeNode.pop_front();

        printf("%d ", pNode->m_nValue);

        if(pNode->m_pLeft)
            dequeTreeNode.push_back(pNode->m_pLeft);

        if(pNode->m_pRight)
            dequeTreeNode.push_back(pNode->m_pRight);
    }
}

  

posted @ 2015-09-23 15:05  枯桃  阅读(136)  评论(0编辑  收藏  举报