103. Binary Tree Zigzag Level Order Traversal(技巧:应用层次遍历+记录每层个数)

来源:互联网 发布:javascript template 编辑:程序博客网 时间:2024/05/21 19:39

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,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its zigzag level order traversal as:

[  [3],  [20,9],  [15,7]]


1.我的答案

突然发现,对于层次遍历的相关题目,可以用队列+每层的节点个数都可以来做


/** * 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>>res;        if(root == NULL)        return res;        queue<TreeNode*>q;        q.push(root);        int count = 1;        int odd = 0;        vector<int>vec;        while(!q.empty()){            TreeNode* t = q.front();            q.pop();            vec.push_back(t->val);            if(t->left){                q.push(t->left);            }            if(t->right){                q.push(t->right);            }            count--;            if(count == 0){                if(odd == 1){                    reverse(vec.begin(), vec.end());                }                odd = !odd;                res.push_back(vec);                vec.clear();                count = q.size();            }        }        return res;    }};




0 0