Day 81 of 100 Days LeetCode Challenge

LeetCode Challenge #102. Binary Tree Level Order Traversal

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:

tree1

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
Video Solution
Java Solution
				
					class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> currAns = new ArrayList<>();

        if(root==null){
            return ans ;
        }
        Queue<TreeNode> main = new ArrayDeque<>();
         Queue<TreeNode> helper= new ArrayDeque<>();

         main.add(root);

         while(main.size()>0){
             TreeNode currNode = main.remove();
             currAns.add(currNode.val);

             if(currNode.left!=null){
                 helper.add(currNode.left);
             }
            if(currNode.right!=null){
                helper.add(currNode.right);
            }
            if(main.size()==0){
                ans.add(currAns);
                currAns = new ArrayList<>();
                main = helper ;
                helper = new ArrayDeque<>();
            }
         }
         return ans ;
    }
}
				
			

Happy Coding with edSlash