二叉树的按行打印及之字形打印

本文介绍两种二叉树的遍历方法:层序遍历和之字形遍历。通过实例展示了如何使用队列实现这两种遍历方式,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 按行打印二叉树

分析:
按行打印二叉树,我们能想到的就是层序遍历二叉树。关键是要按行打印出来,我们可以定义两个变量,一个用来保存下一层元素的个数,一个用来表示当前行打印的元素个数。

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {

        vector<vector<int> > vec;
        vector<int> vec2;

        if (pRoot == NULL)
            return vec;
        int nextLevel = 1;  //下一层元素的个数
        int tobePrint = 1;  //要打印的元素的个数

        queue<TreeNode*> q;
        q.push(pRoot);

        while (!q.empty())
        {
            tobePrint = nextLevel;
            nextLevel = 0;
            vec2.clear();

            while (tobePrint--)
            {
                TreeNode* pCur = q.front();
                vec2.push_back(pCur->val);
                if (pCur->left != NULL)
                {
                    q.push(pCur->left);
                    ++nextLevel;
                }
                if (pCur->right != NULL)
                {
                    q.push(pCur->right);
                    ++nextLevel;
                }
                q.pop();
            }
            vec.push_back(vec2);
        }
        return vec;
    }

};
2. 之字形打印二叉树

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
这里写图片描述
这里写图片描述

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        vector<vector<int> > result;

        if(root==NULL)
            return result;
        bool lefttoright=true;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            int size=q.size();
            vector<int> vec(size);
            for(int i=0;i<size;i++)
            {
               TreeNode* pcur=q.front();
                q.pop();
                int index=(lefttoright)? i:(size-1-i);
                vec[index]=pcur->val;

                if(pcur->left)
                    q.push(pcur->left);
                if(pcur->right)
                    q.push(pcur->right);
            }
            lefttoright=!lefttoright;
            result.push_back(vec);
        }
         return result;   
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值