Problem: 102. 二叉树的层序遍历
文章目录
- 思路
- 复杂度
- Code
思路
👨🏫 路飞
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( n ) O(n) O(n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
Code
/**
* 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<List<Integer>> levelOrder(TreeNode root)
{
List<List<Integer>> ans = new ArrayList<>();
LinkedList<TreeNode> q = new LinkedList<>();
if (root == null)
return ans;
q.add(root);
while (!q.isEmpty())
{
int n = q.size();
ArrayList<Integer> 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;
}
}