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

Leetcode 102. Binary Tree Level Order Traversal

时间:2016-05-17 22:31:36      阅读:180      评论: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.

OJ‘s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.

Here‘s an example:

   1
  /  2   3
    /
   4
         5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

 

分析:二叉树的层序遍历,使用广度优先搜索,建立一个队列q。
每次将队首temp结点出队列的同时,将temp的左孩子和右孩子入队
用size标记入队后的队列长度
row数组始终为当前层的遍历结果,然后用while(size–)语句保证每一次保存入row的只有一层。
每一次一层遍历完成后,将该row的结果存入二维数组v。

技术分享
 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 public:
12     vector<vector<int>> levelOrder(TreeNode* root) {
13         vector<int> row;
14         vector<vector<int>> v;
15         queue<TreeNode *> q;
16         if(root == NULL)
17             return v;
18         q.push(root);
19         TreeNode *temp;
20         while(!q.empty()) {
21             int size = q.size();
22             while(size--) {
23                 temp = q.front();
24                 q.pop();
25                 row.push_back(temp->val);
26                 if(temp->left != NULL) {
27                     q.push(temp->left);
28                 }
29                 if(temp->right != NULL) {
30                     q.push(temp->right);
31                 }
32             }
33             v.push_back(row);
34             row.clear();
35         }
36         return v;
37     }
38 };
View Code

 

Leetcode 102. Binary Tree Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/qinduanyinghua/p/5503422.html

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