【刷题】P174剑指offer:层序遍历二叉树II:分行打印 P176:之字形打印二叉树

层序遍历二叉树II:分行打印二叉树
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

// 变量toBePrinted表示在当前层中还没有打印的节点数
// 变量nextLevel表示下一层节点的数目
void Print(BinaryTreeNode* pRoot)
{
    
    
    if(pRoot == nullptr)
        return;

    std::queue<BinaryTreeNode*> nodes;
    nodes.push(pRoot);
    int nextLevel = 0;
    int toBePrinted = 1;
    while(!nodes.empty())
    {
    
    
        BinaryTreeNode* pNode = nodes.front();
        printf("%d ", pNode->m_nValue);

        if(pNode->m_pLeft != nullptr)
        {
    
    
            nodes.push(pNode->m_pLeft);
            ++nextLevel;
        }
        if(pNode->m_pRight != nullptr)
        {
    
    
            nodes.push(pNode->m_pRight);
            ++nextLevel;
        }

        nodes.pop();
        --toBePrinted;
        if(toBePrinted == 0)
        {
    
    
            printf("\n");
            toBePrinted = nextLevel;
            nextLevel = 0;
        }
    }
}

层序遍历二叉树III:之字形打印二叉树
请实现一个函数按照之字形顺序打印二叉树,即第一层按照从左到右的顺序打印,第二层按照从右到左的顺序打印,其余层以此类推。

void Print(BinaryTreeNode* pRoot)
{
    
    
    if(pRoot == nullptr)
        return;

    std::stack<BinaryTreeNode*> levels[2];
    int current = 0;
    int next = 1;

    levels[current].push(pRoot);
    while(!levels[0].empty() || !levels[1].empty())
    {
    
    
        BinaryTreeNode* pNode = levels[current].top();
        levels[current].pop();

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

        if(current == 0)
        {
    
    
            if(pNode->m_pLeft != nullptr)
                levels[next].push(pNode->m_pLeft);
            if(pNode->m_pRight != nullptr)
                levels[next].push(pNode->m_pRight);
        }
        else
        {
    
    
            if(pNode->m_pRight != nullptr)
                levels[next].push(pNode->m_pRight);
            if(pNode->m_pLeft != nullptr)
                levels[next].push(pNode->m_pLeft);
        }

        if(levels[current].empty())
        {
    
    
            printf("\n");
            current = 1 - current;
            next = 1 - next;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46613023/article/details/115017250