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

Binary Tree Zigzag Level Order Traversal

时间:2014-08-17 18:25:02      阅读:233      评论: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>> zigzags;
 5         vector<TreeNode*> nodeList;
 6         if( root ) { nodeList.push_back( root ); }
 7         while( !nodeList.empty() ) {
 8             vector<TreeNode*> newNodeList;
 9             vector<int> values;
10             for( auto iter = nodeList.rbegin(); iter != nodeList.rend(); ++iter ) {
11                 values.push_back( (*iter)->val );
12                 if( (*iter)->left ) { newNodeList.push_back( (*iter)->left ); }
13                 if( (*iter)->right ) { newNodeList.push_back( (*iter)->right ); }
14             }
15             zigzags.push_back( values );
16             if( newNodeList.empty() ) { break; }
17             nodeList.clear(); values.clear();
18             for( auto iter = newNodeList.rbegin(); iter != newNodeList.rend(); ++iter ) {
19                 values.push_back( (*iter)->val );
20                 if( (*iter)->right ) { nodeList.push_back( (*iter)->right ); }
21                 if( (*iter)->left ) { nodeList.push_back( (*iter)->left ); }
22             }
23             zigzags.push_back( values );
24         }
25         return zigzags;
26     }
27 };

 

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/moderate-fish/p/3917915.html

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