ð 102. äºåæ çå±åºéå
2022幎6æ9æ¥
- algorithm
ð 102. äºåæ çå±åºéå
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* 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>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root == null) {
return res;
}
// root != null
queue.offer(root);
while(!queue.isEmpty()) {
int len = queue.size();
List<Integer> list = new ArrayList<>();
for(int i = 0; i < len; i ++) {
TreeNode cur = queue.poll();
list.add(cur.val);
if(cur.left != null) {
queue.offer(cur.left);
}
if(cur.right != null) {
queue.offer(cur.right);
}
}
res.add(list);
}
return res;
}
}