标签:
LeetCode Premium Subscription
Problems
Pick One
Mock
Articles
Discuss
Book
fengsehng
102. Binary Tree Level Order Traversal My Submissions QuestionEditorial Solution
Total Accepted: 98313 Total Submissions: 302608 Difficulty: Easy
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]
]
/**
* Definition for a binary tree node.
* 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>> all = new ArrayList<List<Integer>>();
Queue<TreeNode> first = new LinkedList<TreeNode>();
Queue<TreeNode> second = new LinkedList<TreeNode>();
if(root == null){
return all;
}
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(root.val);
all.add(tmp);
first.add(root);
while(!first.isEmpty()){
TreeNode node = first.poll();
if(node.left != null){
second.add(node.left);
}
if(node.right != null){
second.add(node.right);
}
if(first.isEmpty()){
List<Integer> tmp1 = new ArrayList<Integer>();
while(!second.isEmpty()){
TreeNode n = second.poll();
first.add(n);
tmp1.add(n.val);
}
if(tmp1.size() != 0){
all.add(tmp1);
}
second.clear();
}
}
return all;
}
}
LeetCode(32)-Binary Tree Level Order Traversal
标签:
原文地址:http://blog.csdn.net/lpjishu/article/details/51088812