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

C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
10 class Solution {
11 public:
12     vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         vector<vector<int>> result;
16         vector<int> level(1);
17         if(root==NULL)
18             return result;
19         queue<TreeNode*> P;
20         queue<TreeNode*> Q;
21         bool flag=true;
22         int p=0;
23         P.push(root);  
24         while(!P.empty())
25         {
26             TreeNode* tmp=P.front();
27             P.pop();
28             if(tmp->left!=NULL)
29             {
30                 Q.push(tmp->left);
31             }
32             if(tmp->right!=NULL)
33             {
34                 Q.push(tmp->right);
35             }
36             if(flag==true)
37             {
38                 level[p++]=tmp->val;
39             }
40             else
41             {
42                 level[p]=tmp->val;
43             }
44             if(P.empty())
45             {
46                 int n=Q.size();
47                 result.push_back(level);
48                 level= vector<int>(n);
49                 queue<TreeNode*> T=P;
50                 P=Q;
51                 Q=T;
52                 flag=!flag;
53                 p=flag==true?0:n1;
54             }
55         }
56         return result;
57     }
58 };
Advertisements
This entry was posted in Stack and Queue, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s