Leetcode 103 Binary Tree Zigzag Level Order Traversal

2018-01-12 14:55:31 浏览数 (1)

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],

代码语言:javascript复制
    3
   / 
  9  20
    /  
   15   7

return its zigzag level order traversal as:

代码语言:javascript复制
[
  [3],
  [20,9],
  [15,7]
]

二叉树蛇形层次遍历。

在第102的基础上加上一个判断奇数偶数层的标记,偶数层reverse一下。

代码语言:javascript复制
/**
 * 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;  
        vector<int> temp;  
        queue<TreeNode*> q,q2;  
        q.push(root);  
        int flag=1;
        while(!q.empty() || !q2.empty())  
        {  
            if(q.empty())  
            {  
                swap(q,q2);
                flag  ;
                if(flag%2) reverse(temp.begin(),temp.end());
                res.push_back(temp);  
                temp.clear();  
            }  
            TreeNode* first=q.front();  
            q.pop();  
            if(!first)continue;  
            temp.push_back(first->val);  
            q2.push(first->left);  
            q2.push(first->right);  
        }  
        return res;
    }
};

0 人点赞