[Remark] P174 sword refers to offer: traverse binary tree in layer sequence II: print by branch P176: print binary tree in zigzag

Traversing the Binary Tree II in Layer Order: Print the Binary Tree
by Lines From top to bottom, the binary tree is printed in layers. The nodes in the same layer are printed in the order from left to right, and each layer is printed to one line.

// 变量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;
        }
    }
}

Layer sequence traversal of the binary tree III: Zigzag printing binary tree
Please implement a function to print the binary tree in zigzag order, that is, the first layer is printed in the order from left to right, the second layer is printed in the order from right to left, and the rest of the layers are printed in this order analogy.

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;
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/115017250