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

LeetCode OJ:Binary Tree Zigzag Level Order Traversal(折叠二叉树遍历)

时间:2015-10-26 11:46:58      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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

简单的bfs而已,不过在bfs的过程中应该注意将相应的数组reverse一下,其实都到最终结果之后在隔行reverse也是可以的,下面给出非递归的版本,用递归同样也很好实现:

 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     struct Node
12     {
13         TreeNode * node;
14         int level;
15         Node(){}
16         Node(TreeNode * n, int lv)
17         : node(n), level(lv){}
18     };
19 public:
20     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
21         vector<vector<int>> ret;
22         if(!root) return ret;
23         vector<int> tmp;
24         int dep = 0;
25         queue<Node>q;
26         q.push(Node(root, 0));
27         while(!q.empty()){
28             Node tmpNode = q.front(); //非递归的使用bfs,借助队列特性
29             if(tmpNode.node->left)
30                 q.push(Node(tmpNode.node->left, tmpNode.level + 1));
31             if(tmpNode.node->right)
32                 q.push(Node(tmpNode.node->right, tmpNode.level + 1));
33             if(dep < tmpNode.level){
34                 if(dep % 2){
35                     reverse(tmp.begin(), tmp.end());
36                 }
37                 ret.push_back(tmp);
38                 tmp.clear();
39                 dep = tmpNode.level;
40             }
41             tmp.push_back(tmpNode.node->val);
42             q.pop();
43         }
44         if(dep % 2){
45             reverse(tmp.begin(), tmp.end());
46         }
47         ret.push_back(tmp);
48         return ret;
49     }
50 };

 

LeetCode OJ:Binary Tree Zigzag Level Order Traversal(折叠二叉树遍历)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4910514.html

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