Thursday, November 1, 2012

Binary Tree zigzag level order traversal

Problem:
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).

Solution:
/**
 * 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> > ans;
        if (!root) return ans;
       
        vector<TreeNode *> nodeVec;
        nodeVec.push_back(root);
       
        int it = 0; //iterator for TreeNode vector.
        int rowIt;
        int rowLimit;
        int whileLoopCounter = 0;    //Used for zig-zagging (reverse output when odd)
       
        while (it < nodeVec.size()) {
            vector<int> row;
            rowLimit = nodeVec.size();
            for (rowIt = it; rowIt < rowLimit; rowIt++) {
                row.push_back(nodeVec[rowIt]->val);
                if (nodeVec[rowIt]->left)
                    nodeVec.push_back(nodeVec[rowIt]->left);
                if (nodeVec[rowIt]->right)
                    nodeVec.push_back(nodeVec[rowIt]->right);
            }
            if ((whileLoopCounter % 2) == 1) {
                row = reverseVec(row);
            }
            ans.push_back(row);
            it = rowLimit;
            whileLoopCounter++;   
        }
        return ans;
    }
    vector<int> reverseVec(vector<int> &row) {
        int it;
        vector<int> sol;
        for (it = row.size() - 1; it >= 0; it--) {
            sol.push_back(row[it]);           
        }
        return sol;
    }
};

No comments:

Post a Comment