【LeetCode】103. Binary Tree Zigzag Level Order Traversal

题目:
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).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
分析:
      这道题的要求是按照Z字形输出一棵二叉树。我的想法是使用BFS来求解这道题。
      设两个变量cur和next来记录当前层次和下一层次还未遍历的结点数,设一个bool变量tag来标志当前层应该从左向右输出还是从右向左输出。
      按BFS将每一个结点遍历一遍,当cur为0时表示当前层的结点已经全部遍历完,则将该层的结点按这一层应该存储的顺序存储到result中。
      这道题的时间复杂度为O(N).

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> result;
        queue<TreeNode*> q;
        vector<int> vv; 
        if(root == NULL)
        return result;
        q.push(root);
        int cur = 0,next = 0,depth = 0;   
        cur++; 
        bool tag = true;      //true表示从左到右,false表示从右到左 
        while(!q.empty())
        {
            TreeNode* temp = q.front();
            vv.push_back(temp->val);
            cur--;
            q.pop(); 
            if(temp->left != NULL)
            {
                q.push(temp->left);
                next++;
            }
            if(temp->right != NULL)
            {
                q.push(temp->right);
                next++;
            }
            if(cur == 0)  //当前层已经遍历完了 
            {

                if(tag)    
                {
                    result.push_back(vector<int>());
                    for(int i = 0;i<vv.size();i++)
                    result[depth].push_back(vv[i]);
                    tag = false;
                } 
                else 
                {
                    result.push_back(vector<int>());
                    for(int i = vv.size()-1;i>=0;i--)
                    result[depth].push_back(vv[i]);
                    tag = true;
                }
                cur = next;
                next = 0;
                depth++;
                vv.clear();
            }


        }
        return result;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值