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
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]这道题是广度优先搜索的模板,BFS用queue来实现
时间O(n) 空间O(n)
要注意:a.有while和for双重循环
b.每次都要给size付一个新值(如果不赋值queue.size在不停变化)
c.queue add 和 delete 是.offer 和.poll
d. queue为什么用linkedlist实现???---Queue是接口, LinkedList可以实现此接口。
public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res= new ArrayList<List<Integer>>(); if (root == null) { return res; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty() ) { int size = queue.size(); List<Integer> tem = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); tem.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } res.add(tem); } return res; } }
没有评论:
发表评论