码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:Binary Tree Zigzag Level Order Traversal

时间:2014-06-14 18:41:40      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   ext   

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:Binary Tree Zigzag Level Order Traversal,布布扣,bubuko.com

Leetcode:Binary Tree Zigzag Level Order Traversal

标签:des   style   class   blog   code   ext   

原文地址:http://www.cnblogs.com/soyscut/p/3787598.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!