Wednesday, September 10, 2014

Binary Tree Zigzag Level Order Traversal (To improve later)

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


 vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        queue<TreeNode *> nextLevel;
        queue<TreeNode *> curLevel;
       
        TreeNode *r = root;
       
        vector<vector<int> > ret;
       
        if (r==NULL)
        return ret;
       
        curLevel.push(r);

        bool l2r=true;
       
        while(1)
        {
            vector<int> tmpV;
       
        while(!curLevel.empty())
        {
            TreeNode *tmp=curLevel.front();
           
            if (tmp!=NULL)
            {
                tmpV.push_back(tmp->val);
                if (tmp->left)
                 nextLevel.push(tmp->left);
                if (tmp->right)
                  nextLevel.push(tmp->right);
            }
           
            curLevel.pop();
        }
       
        if (!l2r)
           reverse(tmpV.begin(),tmpV.end());
          
        l2r=!l2r;
        ret.push_back(tmpV);
       
        if (nextLevel.empty())
        break;
        else
        {
        curLevel.swap(nextLevel);
        }
        }
       
        return ret;
    }

No comments:

Post a Comment