Tuesday, April 13, 2021
More

    Binary Tree Level Order Traversal

    Must Read

    Programmerhttp://www.improgrammer.net
    We started this site to inspire young minds to motivate and encourage them towards Programming Language. In this site you will get programming tutorials, tech, programming facts, programming fun and programming blogs.

    Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / \
      9  20
        /  \
       15   7
    

    return its level order traversal as:

    [
      [3],
      [9,20],
      [15,7]
    ]
    

    Solution:
    Approach 1: Using level order traversal
    public class Solution {
      public List<List<Integer>> levelOrder(TreeNode root) {
    
      List<List<Integer>> result = new ArrayList<>();
    
      Queue<TreeNode> q = new LinkedList<> ();
    
      if(root==null) return result;
    
      q.add(root);
    
      while(!q.isEmpty()){
      List<Integer> subresult = new ArrayList<>();
      int n = q.size();
      for(int i=0; i<n;i++){
      TreeNode node = q.poll();
      subresult.add(node.val);
      if(node.left!=null)q.offer(node.left);
      if(node.right!=null)q.offer(node.right);
      }
      result.add(subresult);
      }
      return result;
      }
    }

    Approach 2:

    /**
    * Definition for a binary tree node.
    * public class TreeNode {
    *    int val;
    *    TreeNode left;
    *    TreeNode right;
    *    TreeNode(int x) { val = x; }
    * }
    */
    public class Solution {
        List<List<Integer>> ans;
        public List<List<Integer>> levelOrder(TreeNode root) {
            ans = new ArrayList<List<Integer>>();
            
            travel(0,root);
            return ans;
        }
        
        private void travel(int level,TreeNode cur){
            if(cur == null) return;
            else{
                if(level >= ans.size()){
                    List<Integer> list = new ArrayList<Integer>();
                    ans.add(list);
                }
                List<Integer> valList = ans.get(level);
                valList.add(cur.val);
                travel(level+1,cur.left);
                travel(level+1,cur.right);
            }
        }
    }
    

     

    Latest Articles

    More Recipes Like This