65-Binary Tree Zigzag Level Order Traversal

  1. Binary Tree Zigzag Level Order Traversal My Submissions QuestionEditorial Solution
    Total Accepted: 60410 Total Submissions: 210160 Difficulty: Medium
    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]
]

思路:参看前面的一篇层次遍历,偶数遍历时逆转便可

/**
 * 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*> levelnode;
        vector<int> row;
        levelnode.push(root);
        int odd=1;
        while(!levelnode.empty()){
            queue<TreeNode*> pre;
            vector<int> tmp;
            while(!levelnode.empty()){
                TreeNode * treetmp=levelnode.front();
                levelnode.pop();
                tmp.push_back(treetmp->val);
                if(treetmp->left!=NULL)pre.push(treetmp->left);
                if(treetmp->right!=NULL)pre.push(treetmp->right);
            }
            if(odd%2==0){
                int tmp_n = tmp.size();
                for(int k=0;k<tmp_n/2;++k){
                    int val = tmp[k];
                    tmp[k] = tmp[tmp_n-k-1];
                    tmp[tmp_n-k-1] = val;
                }
            }
            res.push_back(tmp);
            levelnode = pre;
            odd++;
        }
        return res;
    }
};
posted @ 2016-05-10 21:13  Free_Open  阅读(228)  评论(0编辑  收藏  举报