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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Solution
只要是与Tree和Level相关的问题,大部分都可以用BFS。
-
BFS的套路: 用2个
Queue
或者Stack
。第一个用于存储当前正在扫描层 , 第二个用于存储下一层Object
.- 先把
root
放入queue1
,防止queue1
为空。 - 当
queue1 != null
: 遍历queue1
中每个节点,将其value
放入subArray (每一层的结果)
;同时将其子节点放入queue2
。 - 当
queue1 == null
:
---- 将subArray
加入到最终结果中,清空subArray
;
---- 然后换层:queue1 = queue2;
queue2 = new LinkedList<> ()
- 先把
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<> ();
if (root == null) {
return result;
}
Queue <TreeNode> queue1 = new LinkedList<> ();
Queue <TreeNode> queue2 = new LinkedList<> ();
queue1.add (root);
// subResult for each layer
List<Integer> subArray = new ArrayList<> ();
while (!queue1.isEmpty ()) {
TreeNode current = queue1.poll ();
subArray.add (current.val);
if (current.left != null) {
queue2.add (current.left);
}
if (current.right != null) {
queue2.add (current.right);
}
// queue1 is empty and then swap queue1 and queue2, and add subResult into result
if (queue1.isEmpty ()) {
result.add (subArray);
subArray = new ArrayList<Integer> ();
queue1 = queue2;
queue2 = new LinkedList<TreeNode> ();
}
}
return result;
}
}