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

Binary Tree Zigzag Level Order Traversal

时间:2014-08-16 00:59:49      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   ar   div   

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]
]
代码:
 1 class Solution {
 2 public:
 3     vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
 4         vector<vector<int>> res;
 5         if(!root) return res;
 6         vector<TreeNode *> prev;
 7         vector<TreeNode *> cur;
 8         cur.push_back(root);
 9         bool even = true;
10         while(!cur.empty()){
11             vector<int> lev_res;
12             if(even){
13                 for(vector<TreeNode *>::iterator it = cur.begin(); it != cur.end(); it++)
14                     lev_res.push_back((*it)->val);
15             }else{
16                 for(vector<TreeNode *>::reverse_iterator rit = cur.rbegin(); rit != cur.rend(); rit++)
17                     lev_res.push_back((*rit)->val);
18             }
19             res.push_back(lev_res);
20             even ^= true;
21             prev = cur;
22             cur.clear();
23             for(auto i: prev){
24                 if(i->left) cur.push_back(i->left);
25                 if(i->right) cur.push_back(i->right);
26             }
27         }
28         return res;
29     }
30 };

 

Binary Tree Zigzag Level Order Traversal,布布扣,bubuko.com

Binary Tree Zigzag Level Order Traversal

标签:des   style   blog   color   io   for   ar   div   

原文地址:http://www.cnblogs.com/Kai-Xing/p/3915895.html

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