[備考] P174ソードはオファーを指します:レイヤーシーケンスIIでバイナリツリーをトラバースします:ブランチで印刷しますP176:ジグザグでバイナリツリーを印刷します

バイナリツリーIIをレイヤー順にトラバースする:バイナリツリー
ごとに印刷するバイナリツリーは上から下にレイヤーで印刷されます。同じレイヤー内のノードは左から右に順番に印刷され、各レイヤーは1つに印刷されます。ライン。

// 变量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:二分木のジグザグ印刷二
分木をジグザグの順序で印刷する機能を実装してください。つまり、最初のレイヤーは左から右の順序で印刷され、2番目のレイヤーは順番に印刷されます。右から左に、残りのレイヤーはこの順序で印刷されます。

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