Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal

Total Accepted: 49079 Total Submissions: 179977 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:
    void preorder(TreeNode* root,vector<vector<int>>& res,int depth){
        if(!root) return;
        if(depth==res.size()){
            res.push_back(vector<int>());
        }
        if(depth&1) {
            res[depth].insert(res[depth].begin(),root->val);
        }else{
            res[depth].push_back(root->val);
        }
        preorder(root->left,res,depth+1);
        preorder(root->right,res,depth+1);
    }
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        preorder(root,res,0);
        return res;
    }
};
posted @ 2015-12-18 09:57  zengzy  阅读(150)  评论(0编辑  收藏  举报
levels of contents