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.

Revisions

  1. d-rat created this gist Sep 21, 2021.
    28 changes: 28 additions & 0 deletions levelOrderTraversal.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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;
    }
    }