剑指Offer-32:从上到下打印二叉树

题目1:不分行从上到下打印二叉树

从上倒下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

链接:

剑指Offer(第2版):P171

思路标签:

  • 数据结构:队列

解答:

1. C++
  • 通过举例子我们来寻找解题的思路和过程;
  • 我们可以发现,逐层从左到右打印二叉树的过程需要保存每个节点的左右子节点,利用树节点队列即可实现。
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        std::vector<int> treeVector; 

        if(!root)
            return treeVector;

        std::deque<TreeNode*> dequeTreeNode;

        dequeTreeNode.push_back(root);

        while(dequeTreeNode.size()){
            TreeNode *pNode = dequeTreeNode.front();
            dequeTreeNode.pop_front();
            treeVector.push_back(pNode->val);

            if(pNode->left)
                dequeTreeNode.push_back(pNode->left);
            if(pNode->right)
                dequeTreeNode.push_back(pNode->right);
        }

        return treeVector;
    }
};

扩展:

  • 从上到下按层遍历二叉树,从本质上来说就是广度优先遍历二叉树。
  • 不管是广度优先遍历一幅有向图还是一棵树,都要用到队列。
  • 首先把起始节点(树中为根结点)放入队列,接下来每次从队列的头部取出一个节点,遍历这个节点后把它能到达的节点(树中为子结点)都依次放入队列。重复这个遍历过程,直到队列中的节点全部都遍历为止。

C++相关


题目2:分行从上到下打印二叉树

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

链接:

剑指Offer(第2版):P174

思路标签:

  • 数据结构:队列

解答:

1. C++
  • 同样,使用队列来保存将要打印的结点,但是为了将二叉树的每一层分别打印在单独的一行,我们需要使用二维数组来对结果进行保存。
  • 同时,也可以不使用二维数组保存,在进行的过程中,直接打印输出,这时需要两个变量,一个变量表示当前层中还没有打印的节点数,另一个变量表示下一层的节点数目。
/*
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::vector<vector<int>> treeVector;
            if(pRoot == nullptr)
                return treeVector;

            std::queue<TreeNode*> queueNodes;
            queueNodes.push(pRoot);

            while(!queueNodes.empty()){
                std::vector<int> temp;
                int n = queueNodes.size();
                while(n--){
                    TreeNode* pNode = queueNodes.front();
                    temp.push_back(pNode->val);
                    if(pNode->left)
                        queueNodes.push(pNode->left);
                    if(pNode->right)
                        queueNodes.push(pNode->right);
                    queueNodes.pop();
                }
                treeVector.push_back(temp);
            }
            return treeVector;
        }
};
#include <cstdio>
#include "..\Utilities\BinaryTree.h"
#include <queue>

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

c++相关:


题目3:之字形打印二叉树

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

链接:

剑指Offer(第2版):P176

思路标签:

  • 数据结构:

解答:

1. C++
  • 同样以举例子的形式来对问题进行分析,我们可以发现,每次对下一层的子结点进行保存的时候,是以先入后出的形式进行打印的,故使用栈来实现;
  • 因为是实现分层打印,所以当前层和下一层需要使用两个不同的栈来实现;
  • 我们在打印某一层的结点时,把下一层的子结点保存到相应的栈里。如果当前打印的是奇数层(第一、第三层等),则先保存左子结点再保存右子结点到第一个栈中;如果当前打印的是偶数层(第二、第四层等),则先保存右子结点再保存左子结点到第二个栈中。
  • 同样如上,一种是保存到二维数组中,一种是直接在遍历的过程中打印输出,思想是相同的。
/*
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::vector<vector<int>> treeVector;

        if(pRoot == nullptr)
            return treeVector;

        std::stack<TreeNode*> levels[2];
        int current = 0;
        int next = 1;
        levels[current].push(pRoot);
        while(!levels[0].empty() || !levels[1].empty()){
            std::vector<int> temp;
            int n = levels[current].size();
            while(n--){
                TreeNode* pNode = levels[current].top();
                temp.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);
                }

                levels[current].pop();
            }
            treeVector.push_back(temp);
            current = 1 - current;
            next = 1 - next;
        }

        return treeVector;
    }
};
#include <cstdio>
#include "..\Utilities\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[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;
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值