首页 > 其他 > 详细

Binary Tree Zigzag Level Order Traversal

时间:2015-06-20 01:24:40      阅读:241      评论:0      收藏:0      [点我收藏+]

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

Code:

 1 vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
 2        deque<TreeNode*>a;
 3        deque<TreeNode*>b;
 4        if (root)
 5             a.push_back(root);
 6         
 7        TreeNode*p = NULL;
 8        vector<vector<int>> result;
 9        
10        while (!a.empty() || !b.empty())
11        {
12            vector<int>temp;
13            if (!a.empty() )
14            {
15                 while (!a.empty() )
16                 {
17                p = a.front();
18                a.pop_front();
19                temp.push_back(p->val);
20                if (p->left)
21                     b.push_back(p->left);
22                 if (p->right)
23                     b.push_back(p->right);
24                 }
25                 result.push_back(temp);
26            }
27            else
28            {
29             while (!b.empty())
30            {
31                p = b.front();
32                b.pop_front();
33                temp.push_back(p->val);
34                if (p->left)
35                     a.push_back(p->left);
36                if (p->right)
37                     a.push_back(p->right);
38            }
39            result.push_back(temp);
40            }
41        }
42        for (int i = 1; i < result.size(); i+=2)
43        {
44            reverse(result[i].begin(),result[i].end());
45        }
46        return result; 
47     }

 

Binary Tree Zigzag Level Order Traversal

原文:http://www.cnblogs.com/happygirl-zjj/p/4589934.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!