-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Description
BFS
时间复杂度O(n) 空间复杂度O(n)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int sz = queue.size();
List<Integer> line = new ArrayList<>();
for (int i = 0; i < sz; i++) {
TreeNode cur = queue.poll();
line.add(cur.val);
if (cur.left != null)
queue.offer(cur.left);
if (cur.right != null)
queue.offer(cur.right);
}
result.add(line);
}
return result;
}
}