Saturday, October 19, 2013

Binary Tree Zigzag Level Order Traversal [Leetcode]

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]
] 
Solution: the basic idea is similar to Binary Tree Level Order Traversal I and II. Here we use BFS.
/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<vector<int> > ret;
        if(root==NULL)
            return ret;
        queue<TreeNode*> q;
        q.push(root);
        int curNum=1, nxtNum=0;
        vector<int> r;
        bool flip = false;
        while(!q.empty()){
            TreeNode* tmp = q.front();
            q.pop();
            r.push_back(tmp->val);
            if(tmp->left!=NULL){
                q.push(tmp->left);
                nxtNum++;
            }
            if(tmp->right!=NULL){
                q.push(tmp->right);
                nxtNum++;
            }
            curNum--;
            if(curNum==0){
                if(flip)
                    reverse(r.begin(), r.end());
                ret.push_back(r);
                r.clear();
                flip = !flip;
                curNum = nxtNum;
                nxtNum=0;
            }
        }
        return ret;
    }
}; 

No comments:

Post a Comment