题目链接: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] 
] 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1 
  / \ 
 2   3 
    / 
   4 
    \ 
     5 

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

这道题的要求是Zigzag方式遍历二叉树,即分层遍历,先是从左到右,接着从右到左,然后从左到右,接着从右到左,以此类推。

和Binary Tree Level Order Traversal类似,由于需要把每层的节点分别放入到数组中,因此需要引入变量n记录每层的节点数量。然而由于需要按Zigzag方式遍历,因此在偶数层需要反转即可(假设根节点为第12层)。再剩下的,就是广度优先遍历的方法了。

时间复杂度:O(n)

空间复杂度:O(n)

 1 class Solution
 2 {
 3 public:
 4     vector<vector<int> > zigzagLevelOrder(TreeNode *root)
 5     {
 6         vector<vector<int> > vvi;
 7         
 8         if(root == NULL)
 9             return vvi;
10         
11         queue<TreeNode *> q;
12         q.push(root);
13         bool zigzag = false;
14         while(!q.empty())
15         {
16             vector<int> vi;
17             for(int i = 0, n = q.size(); i < n; ++ i)
18             {
19                 TreeNode *temp = q.front();
20                 q.pop();
21                 if(temp -> left != NULL)
22                     q.push(temp -> left);
23                 if(temp -> right != NULL)
24                     q.push(temp -> right);
25                 vi.push_back(temp -> val);
26             }
27             if(zigzag)
28                 reverse(vi.begin(), vi.end());
29             vvi.push_back(vi);
30             zigzag = !zigzag;
31         }
32         
33         return vvi;
34     }
35 };