Skip to content

Instantly share code, notes, and snippets.

@d-rat
Created September 21, 2021 14:21
Show Gist options
  • Save d-rat/2cdd54ea90f3db62312e3489d4eb42e6 to your computer and use it in GitHub Desktop.
Save d-rat/2cdd54ea90f3db62312e3489d4eb42e6 to your computer and use it in GitHub Desktop.
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans=new ArrayList<>();
if(root==null) return ans;
List<Integer> level=new ArrayList<>();
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
q.offer(null);
while(!q.isEmpty()){
TreeNode temp=q.poll();
if(temp==null){
ans.add(level);
level.clear();
if(!q.isEmpty()){
q.offer(null);
}
} else {
level.add(temp.val);
if(temp.left!=null) q.offer(temp.left);
if(temp.right!=null) q.offer(temp.right);
}
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment