时间复杂度:
添加时间复杂度, 示例: O ( n ) O(n) O(n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
/**
* 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> levelOrder(TreeNode root)
{
List> ans = new ArrayList<>();
LinkedList q = new LinkedList<>();
if (root == null)
return ans;
q.add(root);
while (!q.isEmpty())
{
int n = q.size();
ArrayList list = new ArrayList<>(n);
while (n-- > 0)
{
TreeNode node = q.poll();
list.add(node.val);
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
}
ans.add(list);
}
return ans;
}
}