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.
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}".思路:利用队列进行处理就行了,每次记录入队的有几个,就是下一层要访问的了
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
result.clear();
if (root == null) return result;
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
int level = 0, count = 1;
while (!q.isEmpty()) {
List<Integer> tmp = new ArrayList<Integer>();
tmp.clear();
level = 0;
for (int i = 0; i < count; i++) {
root = q.pollFirst();
tmp.add(root.val);
if (root.left != null) {
q.add(root.left);
++level;
}
if (root.right != null) {
q.add(root.right);
++level;
}
}
count = level;
result.add(tmp);
}
return result;
}
}
LeetCode Binary Tree Level Order Traversal
原文:http://blog.csdn.net/u011345136/article/details/45347741