一、题目
二、代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution
{
public List<List<Integer>> levelOrder(TreeNode root)
{
if(root==null) return new LinkedList<List<Integer>>();
List<List<Integer>> return_list = new LinkedList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty())
{
int temp_size = queue.size();
int i;
List<Integer> temp_list = new LinkedList<Integer>();
for(i = 0; i< temp_size;i++ )
{
TreeNode temp_node = queue.poll();
if(temp_node.left!=null) queue.offer(temp_node.left);
if(temp_node.right!=null) queue.offer(temp_node.right);
temp_list.add(temp_node.val);
}
System.out.println(temp_list);
return_list.add(temp_list);
// temp_list.clear();
}
return return_list;
}
}
三、运行结果
四、附录
二刷
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution
{
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> levelOrder(TreeNode root)
{
if(root == null) return res;
Deque<TreeNode> queue1 = new LinkedList<>();
int i;
int length;
queue1.addLast(root);
while(queue1.size()!=0)
{
List<Integer> temp_list = new LinkedList<>();
length = queue1.size();
for(i=0;i<length;i++)
{
TreeNode temp_node = queue1.peekFirst();
queue1.removeFirst();
temp_list.add(temp_node.val);
if(temp_node.left!=null) queue1.add(temp_node.left);
if(temp_node.right!=null) queue1.add(temp_node.right);
}
res.add(temp_list);
}
return res;
}
}