Sunday, February 24, 2013

Binary Tree Zigzag Level Order Traversal

/*
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]
]
*/
/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int>> result;
        vector<int> line;
        if (root==NULL) return result;
        queue<TreeNode*> q;
        int leftValue = 2000;
        TreeNode *leftFirst= new TreeNode(leftValue);
        int rightValue = -2000;
        TreeNode *rightFirst = new TreeNode(rightValue);
       
        TreeNode *curr;
        q.push(root);
        q.push(leftFirst);
        bool fromLeft = true;
       
        while(!q.empty()){
          curr=q.front();
          q.pop();
          if(curr!=leftFirst && curr!=rightFirst){
            if(curr->left) q.push(curr->left);
            if(curr->right) q.push(curr->right);
            if(fromLeft) line.push_back(curr->val);
            else line.insert(line.begin(),curr->val);
          }
          if(curr==rightFirst){
            fromLeft = !fromLeft;
            result.push_back(line);
            line.clear();
            if((!q.empty()) && q.front()!=rightFirst && q.front()!=leftFirst){
            q.push(leftFirst);
            }
          }
          if(curr==leftFirst){
            fromLeft = !fromLeft;
            result.push_back(line);
            line.clear();
            if((!q.empty()) && q.front()!=rightFirst && q.front()!=leftFirst){
            q.push(rightFirst);
            }
          }
        }
       
        return result;
    }
};

No comments:

Post a Comment