刷题顺序按照代码随想录建议
题目描述
英文版描述
Given the root
of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1] Output: [[1]]
Example 3:
Input: root = [] Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]
. -1000 <= Node.val <= 1000
英文版地址
中文版描述
给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入: root = [3,9,20,null,null,15,7] 输出: [[3],[9,20],[15,7]]
示例 2:
输入: root = [1] 输出: [[1]]
示例 3:
输入: root = [] 输出: []
提示:
- 树中节点数目在范围
[0, 2000]
内 -1000 <= Node.val <= 1000
中文版地址
解题方法
java
/**
* 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 {
List<List<Integer>> result = new LinkedList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return result;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.addLast(root);
int size = deque.size();
List<Integer> line = new LinkedList<>();
while (size-- > 0) {
TreeNode treeNode = deque.pollFirst();
TreeNode left = treeNode.left;
if (left != null) {
deque.addLast(left);
}
TreeNode right = treeNode.right;
if (right != null) {
deque.addLast(right);
}
line.add(treeNode.val);
if (size == 0) {
result.add(new LinkedList<>(line));
line = new LinkedList<>();
size = deque.size();
}
}
return result;
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是二叉树的节点数,每一个节点进一次队列出一次队列
- 空间复杂度:O(n),其中 n 是二叉树中的节点个数,空间复杂度取决于队列开销,队列中的节点个数不会超过 n