Open Ni-Guvara opened 1 year ago
/**
* 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<>();
if(root == null){
return ans;
}
LinkedList<TreeNode> que = new LinkedList<>();
que.addFirst(root);
while(!que.isEmpty()){
List<Integer> row = new ArrayList<>();
int size = que.size();
for(int i = 0; i < size; i++){
TreeNode cur = que.pollFirst();
row.add(cur.val);
if(cur.left != null){
que.addLast(cur.left);
}
if(cur.right != null){
que.addLast(cur.right);
}
}
ans.add(row);
}
return ans;
}
}