《剑指offer》第三十二题III:之字形打印二叉树

// 面试题32(三):之字形打印二叉树
// 题目:请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺
// 序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,
// 其他行以此类推。

#include <cstdio>
#include "BinaryTree.h"
#include <stack>

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[current].empty() || !levels[next].empty())
    {
        BinaryTreeNode* pNode = levels[current].top();
        printf("%d ", pNode->m_nValue);
        levels[current].pop();

        if (current == 0) //当前打印奇数序列, 从左到右
        {
            if (pNode->m_pLeft)
                levels[next].push(pNode->m_pLeft);
            if (pNode->m_pRight)
                levels[next].push(pNode->m_pRight);
        }
        else //当前打印偶数序列, 从右到左
        {
            if (pNode->m_pRight)
                levels[next].push(pNode->m_pRight);
            if (pNode->m_pLeft)
                levels[next].push(pNode->m_pLeft);
        }

        if (levels[current].empty()) //如果当前节点打印完了
        {
            printf("\n");
            current = 1 - current;
            next = 1 - next;
        }
    }
}

// ====================测试代码====================
//            8
//        6      10
//       5 7    9  11
void Test1()
{
    BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
    BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
    BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
    BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
    BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
    BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
    BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);

    ConnectTreeNodes(pNode8, pNode6, pNode10);
    ConnectTreeNodes(pNode6, pNode5, pNode7);
    ConnectTreeNodes(pNode10, pNode9, pNode11);

    printf("====Test1 Begins: ====\n");
    printf("Expected Result is:\n");
    printf("8 \n");
    printf("10 6 \n");
    printf("5 7 9 11 \n\n");

    printf("Actual Result is: \n");
    Print(pNode8);
    printf("\n");

    DestroyTree(pNode8);
}

//            5
//          4
//        3
//      2
void Test2()
{
    BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
    BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);
    BinaryTreeNode* pNode3 = CreateBinaryTreeNode(3);
    BinaryTreeNode* pNode2 = CreateBinaryTreeNode(2);

    ConnectTreeNodes(pNode5, pNode4, nullptr);
    ConnectTreeNodes(pNode4, pNode3, nullptr);
    ConnectTreeNodes(pNode3, pNode2, nullptr);

    printf("====Test2 Begins: ====\n");
    printf("Expected Result is:\n");
    printf("5 \n");
    printf("4 \n");
    printf("3 \n");
    printf("2 \n\n");

    printf("Actual Result is: \n");
    Print(pNode5);
    printf("\n");

    DestroyTree(pNode5);
}

//        5
//         4
//          3
//           2
void Test3()
{
    BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
    BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);
    BinaryTreeNode* pNode3 = CreateBinaryTreeNode(3);
    BinaryTreeNode* pNode2 = CreateBinaryTreeNode(2);

    ConnectTreeNodes(pNode5, nullptr, pNode4);
    ConnectTreeNodes(pNode4, nullptr, pNode3);
    ConnectTreeNodes(pNode3, nullptr, pNode2);

    printf("====Test3 Begins: ====\n");
    printf("Expected Result is:\n");
    printf("5 \n");
    printf("4 \n");
    printf("3 \n");
    printf("2 \n\n");

    printf("Actual Result is: \n");
    Print(pNode5);
    printf("\n");

    DestroyTree(pNode5);
}

void Test4()
{
    BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);

    printf("====Test4 Begins: ====\n");
    printf("Expected Result is:\n");
    printf("5 \n\n");

    printf("Actual Result is: \n");
    Print(pNode5);
    printf("\n");

    DestroyTree(pNode5);
}

void Test5()
{
    printf("====Test5 Begins: ====\n");
    printf("Expected Result is:\n");

    printf("Actual Result is: \n");
    Print(nullptr);
    printf("\n");
}

//        100
//        /
//       50
//         //         150
void Test6()
{
    BinaryTreeNode* pNode100 = CreateBinaryTreeNode(100);
    BinaryTreeNode* pNode50 = CreateBinaryTreeNode(50);
    BinaryTreeNode* pNode150 = CreateBinaryTreeNode(150);

    ConnectTreeNodes(pNode100, pNode50, nullptr);
    ConnectTreeNodes(pNode50, nullptr, pNode150);

    printf("====Test6 Begins: ====\n");
    printf("Expected Result is:\n");
    printf("100 \n");
    printf("50 \n");
    printf("150 \n\n");

    printf("Actual Result is: \n");
    Print(pNode100);
    printf("\n");
}

//                8
//        4              12
//     2     6       10      14
//   1  3  5  7     9 11   13  15
void Test7()
{
    BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
    BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);
    BinaryTreeNode* pNode12 = CreateBinaryTreeNode(12);
    BinaryTreeNode* pNode2 = CreateBinaryTreeNode(2);
    BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
    BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
    BinaryTreeNode* pNode14 = CreateBinaryTreeNode(14);
    BinaryTreeNode* pNode1 = CreateBinaryTreeNode(1);
    BinaryTreeNode* pNode3 = CreateBinaryTreeNode(3);
    BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
    BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
    BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
    BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);
    BinaryTreeNode* pNode13 = CreateBinaryTreeNode(13);
    BinaryTreeNode* pNode15 = CreateBinaryTreeNode(15);

    ConnectTreeNodes(pNode8, pNode4, pNode12);
    ConnectTreeNodes(pNode4, pNode2, pNode6);
    ConnectTreeNodes(pNode12, pNode10, pNode14);
    ConnectTreeNodes(pNode2, pNode1, pNode3);
    ConnectTreeNodes(pNode6, pNode5, pNode7);
    ConnectTreeNodes(pNode10, pNode9, pNode11);
    ConnectTreeNodes(pNode14, pNode13, pNode15);

    printf("====Test7 Begins: ====\n");
    printf("Expected Result is:\n");
    printf("8 \n");
    printf("12 4 \n");
    printf("2 6 10 14 \n");
    printf("15 13 11 9 7 5 3 1 \n\n");

    printf("Actual Result is: \n");
    Print(pNode8);
    printf("\n");

    DestroyTree(pNode8);
}

int main(int argc, char* argv[])
{
    Test1();
    Test2();
    Test3();
    Test4();
    Test5();
    Test6();
    Test7();

    return 0;
}

测试代码

分析:举例分析,奇偶数行打印顺序不同,所以下一行压入栈顺序也不同。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {

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

        std::vector<vector<int> > printTreeNode;
        std::vector<int> printTemp;

        if (pRoot == nullptr)
            return printTreeNode;

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

            printTemp.push_back(pNode->val);

            if (current == 0)
            {
                if (pNode->left)
                    levels[next].push(pNode->left);
                if (pNode->right)
                    levels[next].push(pNode->right);
            }
            else
            {
                if (pNode->right)
                    levels[next].push(pNode->right);
                if (pNode->left)
                    levels[next].push(pNode->left);
            }

            if (levels[current].empty())
            {
                printTreeNode.push_back(printTemp);
                printTemp.clear();
                current = 1 - current;
                next = 1 - next;
            }
        }
        return printTreeNode;
    }

};

牛客网提交代码

原文地址:https://www.cnblogs.com/ZSY-blog/p/12602375.html

时间: 2024-07-30 16:39:01

《剑指offer》第三十二题III:之字形打印二叉树的相关文章

《剑指offer》第二十二题(链表中倒数第k个结点)

// 面试题22:链表中倒数第k个结点 // 题目:输入一个链表,输出该链表中倒数第k个结点.为了符合大多数人的习惯, // 本题从1开始计数,即链表的尾结点是倒数第1个结点.例如一个链表有6个结点, // 从头结点开始它们的值依次是1.2.3.4.5.6.这个链表的倒数第3个结点是 // 值为4的结点. //O(n)的解法:维护两个指针,让A走B前头,前K步,A到头,B就是解了,但是这个问题在于程序鲁棒性 #include <iostream> #include "List.h&q

《剑指offer》第十二题:矩阵中的路径

// 面试题12:矩阵中的路径 // 题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有 // 字符的路径.路径可以从矩阵中任意一格开始,每一步可以在矩阵中向左.右. // 上.下移动一格.如果一条路径经过了矩阵的某一格,那么该路径不能再次进入 // 该格子.例如在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字 // 母用下划线标出).但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个 // 字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入

《剑指offer》第二十二题:链表中倒数第k个结点

// 面试题22:链表中倒数第k个结点 // 题目:输入一个链表,输出该链表中倒数第k个结点.为了符合大多数人的习惯, // 本题从1开始计数,即链表的尾结点是倒数第1个结点.例如一个链表有6个结点, // 从头结点开始它们的值依次是1.2.3.4.5.6.这个链表的倒数第3个结点是 // 值为4的结点. #include <cstdio> #include "List.h" ListNode* FindKthToTail(ListNode* pListHead, unsi

二叉树层次遍历(剑指Offer面试题32:从上到下打印二叉树)

图1所示为二叉树的层次遍历,即按照箭头所指方向,按照1.2.3的层次顺序,对二叉树每个节点进行访问 (此图反映的是自左至右的层次遍历,自右至左的方式类似). 要进行层次遍历,需要建立一个队列.先将二叉树头节点入队列,然后出队列,访问该节点, 如果它有左子树,则将左子树的根结点入队:如果它有右子树,则将右子树的根结点入队.然后出队列,对出队节点访问, 如此反复直到队列为空为止. 1 import java.util.*; 2 class TreeNode 3 { 4 int val; 5 Tree

《剑指offer》第十五题:二进制中1的个数

// 面试题15:二进制中1的个数 // 题目:请实现一个函数,输入一个整数,输出该数二进制表示中1的个数.例如 // 把9表示成二进制是1001,有2位是1.因此如果输入9,该函数输出2. #include <cstdio> int NumberOf1_Solution1(int n) { //主要思路:逐位与运算 int count = 0; unsigned int flag = 1; while (flag) { if (n & flag) ++count; flag = fl

《剑指offer》第十六题(数值的整数次方)

// 面试题:数值的整数次方 // 题目:实现函数double Power(double base, int exponent),求base的exponent // 次方.不得使用库函数,同时不需要考虑大数问题. #include <iostream> #include <cmath> using namespace std; bool g_InvalidInput = false;//使用全局变量作为错误处理方式 bool equal(double num1, double nu

《剑指offer》第二十四题(反转链表)

// 面试题24:反转链表 // 题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的 // 头结点. #include <iostream> #include "List.h" ListNode* ReverseList(ListNode* pHead) { ListNode* pReversedHead = nullptr;//设置三个节点变量,第一是已经被反转的头节点(原链表尾节点) ListNode* pNode = pHead;//第二个是当前节

《剑指offer》第十四题(剪绳子)

// 面试题:剪绳子 // 题目:给你一根长度为n绳子,请把绳子剪成m段(m.n都是整数,n>1并且m≥1). // 每段的绳子的长度记为k[0].k[1].…….k[m].k[0]*k[1]*…*k[m]可能的最大乘 // 积是多少?例如当绳子的长度是8时,我们把它剪成长度分别为2.3.3的三段,此 // 时得到最大的乘积18. #include <iostream> #include <cmath> // ====================动态规划=========

《剑指offer》第十八题:在O(1)时间删除链表结点

// 面试题18(一):在O(1)时间删除链表结点 // 题目:给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该 // 结点. #include <cstdio> #include "List.h" void DeleteNode(ListNode** pListHead, ListNode* pToBeDeleted) { if (pListHead == nullptr || pToBeDeleted == nullptr) return; //多个