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

leetcode 102. Binary Tree Level Order Traversal

时间:2015-02-17 19:52:50      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7

 

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

[Solution]

二叉树层次遍历,即广度遍历,使用队列做辅助。

 1 vector<vector<int> > levelOrder(TreeNode *root) 
 2     {
 3         vector<vector<int> > result;
 4         vector<int> line;
 5         queue<TreeNode *> qtree;
 6         TreeNode *visit = root;
 7         int current_level_size = 1, next_level_size = 0;
 8         
 9         if (visit != NULL)
10             qtree.push(visit);
11         while (!qtree.empty())
12         {
13             visit = qtree.front();
14             qtree.pop();
15             current_level_size--;
16             line.push_back(visit->val);
17             
18             if (visit->left != NULL)
19             {
20                 qtree.push(visit->left);
21                 next_level_size++;
22             }
23             if (visit->right != NULL)
24             {
25                 qtree.push(visit->right);
26                 next_level_size++;
27             }
28             if (current_level_size == 0) // all this level nodes are visited.
29             {
30                 result.push_back(line);
31                 line.clear();
32                 current_level_size = next_level_size;
33                 next_level_size = 0;
34             }
35         }
36 
37         return result;
38     }

 

leetcode 102. Binary Tree Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4295385.html

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