Monday, March 7, 2016

LeetCode Q103: 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]
]


Solution: Similar to Q102, but need a flag to indicate whether to reverse accessed nodes at current layer.

/**
* 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:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int> > res;
if(root==NULL)
return res;
queue<TreeNode*> Q;
Q.push(root);
int marker=0;
int cur=1;
int next=0;
vector<int> tmp;
while(!Q.empty()){
TreeNode* front = Q.front();
Q.pop();
if(front!=NULL){
tmp.push_back(front->val);
Q.push(front->left);
Q.push(front->right);
next+=2;
}
cur--;
if(cur==0&&!tmp.empty()){
if(marker==1)
reverse(tmp.begin(), tmp.end());
res.push_back(tmp);
tmp.clear();
cur=next;
next=0;
marker=marker^1;
}
}
return res;
}
};
view raw Q103.cpp hosted with ❤ by GitHub

No comments:

Post a Comment