之字形打印二叉树

题目描述

请实现一个函数按照之字形顺序从上向下打印二叉树。

即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

样例
Input: [8, 12, 2, null, null, 6, null, 4, null, null, null]
Output:[[8], [2, 12], [6, 4]]

解题思路

  • 描述

    同样是树的层次遍历。

    在初始化时,加入root和NULL两个节点。当出队元素为NULL,表明一层结束。

    根据层数翻转存储每层元素的数组即可。

  • 实现代码:

    vector<vector<int>> printFromTopToBottom(TreeNode* root) {
        vector<vector<int> > res; // 存放结果
        vector<int> cres; // 存放每层元素
        if(!root) // 为空,直接返回res
        {
            return res;
        }
    
        bool level = true;
        queue<TreeNode*> q;
        TreeNode* tmp;
        q.push(root);
        q.push(NULL);
    
        while(!q.empty())
        {
            tmp = q.front();
            q.pop();
    
            if(tmp) // 出队元素非空,按照层次遍历正常情况处理
            {
                cres.push_back(tmp->val);
                if(tmp->left)
                {
                    q.push(tmp->left);
                }
                if(tmp->right)
                {
                    q.push(tmp->right);
                }
            }
            else
            {
                if(cres.empty()) // 当该层元素为空,表明树已遍历完成
                {
                    break;
                }
                if(!level) // level为false
                {
                    reverse(cres.begin(),cres.end());
                }
                res.push_back(cres); // 加入到结果中
                cres.clear(); // 清空
                q.push(NULL); // 加入NULL,标记下一层的结束
                level = !level;
            }
    
    
        }
    
        return res;
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值