首页 > 代码库 > LeetCode103 Binary Tree Zigzag Level Order Traversal

LeetCode103 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).(Medium)

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

 

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

 

分析:

层序遍历还要交叉输出。所以先采用队列进行层序编译(存放一层在队列中,每次循环先读这一队列的长度,然后以此把他们的值存在vector里,并且把存在的左右孩子压入队列)。

因为要交叉输出,所以采用一个flag,每次循环后flag正负号改变。负号时倒序输出。

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
13         vector<vector<int>> result;
14         if (root == nullptr) {
15             return result;
16         }
17         queue<TreeNode* >que;
18         que.push(root);
19         int flag = 1;
20         while(!que.empty()) {
21             int sz = que.size();
22             vector<int> temp;
23             for (int i = 0; i < sz; ++i) {
24                 TreeNode* cur = que.front();
25                 que.pop();
26                 temp.push_back(cur -> val);
27                 if (cur -> left != nullptr) {
28                     que.push(cur -> left);
29                 }
30                 if (cur -> right != nullptr) {
31                     que.push(cur -> right);
32                 }
33             }
34             if (flag == -1) {
35                  reverse(temp.begin(), temp.end());
36                  result.push_back(temp);  
37                  flag = 1;
38             }
39             else {
40                 result.push_back(temp);  
41                 flag = -1;
42             }
43 
44         }
45         return result;
46     }
47 };

 

LeetCode103 Binary Tree Zigzag Level Order Traversal