leetcode--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,#,#,15,7},
3
/ |
9 20
/ |
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

思路:

  1. 在层序遍历的基础上,修改进出队列的操作顺序。
  2. 或者是按照层次的奇偶性来判断层次遍历的结果是否应该reverse,后面的思路编码实现较简单。

下面是思路1的代码实现,我们采用deque以得到更多的队列操作。

/**
 * Definition for binary tree
 * 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> >  vv; 
        if(root == NULL) return vv;
        deque<TreeNode* > q;
        TreeNode* temp = NULL;
        q.push_back(root);
        int cnt = 0;
        while(!q.empty()) {
            int len = q.size();
            vector<int> t;
            if(cnt%2 == 0) {
                for(int i = 0;i < len; i++) {
                    temp = q.front();
                    q.pop_front();
                    if(temp->left) q.push_back(temp->left);
                    if(temp->right) q.push_back(temp->right);
                    t.push_back(temp->val);
                }
                
            }else {
                for(int i = 0;i < len; i++) {
                    temp = q.back();
                    q.pop_back();
                    if(temp->right) q.push_front(temp->right);
                    if(temp->left) q.push_front(temp->left);
                    t.push_back(temp->val);
                }
            }
            vv.push_back(t);
            cnt++;
        }
        return vv;
    }
};

下面是思路二的代码:

/**
 * Definition for binary tree
 * 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> >  vv; 
        if(root == NULL) return vv;
        queue<TreeNode* > q;
        TreeNode* temp = NULL;
        q.push(root);
        int cnt = 1;
        while(!q.empty()) {
            int len = q.size();
            vector<int> t;
            for(int i = 0;i < len; i++) {
                temp = q.front();
                q.pop();
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
                t.push_back(temp->val);
            }
            if(cnt % 2 == 0) reverse(t.begin(),t.end());
            vv.push_back(t);
            cnt++;
        }
        return vv;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容