👨🏫 题目地址
- 时间复杂度: 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<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();//n记录当前层的结点个数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;}
}
😋 顺序表写法
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {if (root == null) return List.of();List<List<Integer>> ans = new ArrayList<>();List<TreeNode> cur = new ArrayList<>();cur.add(root);while (!cur.isEmpty()) {List<TreeNode> nxt = new ArrayList<>();List<Integer> vals = new ArrayList<>(cur.size()); // 容量已知for (TreeNode node : cur) {vals.add(node.val);if (node.left != null) nxt.add(node.left);if (node.right != null) nxt.add(node.right);}cur = nxt;ans.add(vals);}return ans;}
}
👨🏫 参考题解