Leetcode:Binary Tree Zigzag Level Order Traversal

Description:

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

 分析: 题目要给出二叉树的zigzag Z型遍历,其本质应该是二叉树的宽搜,然后根据层数来确定每一层是否翻转。 

这主要点就在于宽搜时需要知道当前在第几层,所以需要两个queue来做。 这个是一个常用技巧

 1 /**
 2  * Definition for binary tree
 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==NULL) return result;
15         
16         queue<TreeNode* > q,qadd;
17         q.push(root);
18         vector<int> level;
19         int nowlevel = 1;
20         while(!q.empty())
21         {
22             TreeNode *one = q.front();
23             level.push_back(one->val);
24             if(one->left!=NULL) qadd.push(one->left);
25             if(one->right!=NULL) qadd.push(one->right);
26             
27             q.pop();
28             if(q.empty())
29             {
30                 if(nowlevel%2==0) reverse(level.begin(),level.end());
31                 result.push_back(level);
32                 level.clear();
33                 nowlevel++;
34                 swap(q,qadd);
35             }
36         }
37         return result;
38     }
39 };

 

你可能感兴趣的:(LeetCode)