BFS二叉树2

题目

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
if (root != null) queue.add(root);
while (!queue.isEmpty()) {
List<Integer> tmp = new ArrayList<>();
for (int i=queue.size(); i>0; i--) {
TreeNode node = queue.poll();
tmp.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
res.add(tmp);
}
return res;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×