Left View

 avatar
unknown
java
7 days ago
868 B
1
Indexable
class Solution {
    // Function to return list containing elements of left view of binary tree.
    ArrayList<Integer> leftView(Node root) {
        Queue<Node> q = new LinkedList<>();
        
        ArrayList<Integer> arr = new ArrayList<>();
        
        if(root==null)
        return arr;
        
        q.add(root);
        
        while(!q.isEmpty())
        {
            int cnt = q.size();
            for(int i=0;i<cnt;++i)
            {
                Node curr = q.peek();
                q.poll();
                
                if(i==0)
                arr.add(curr.data);
                
                if(curr.left!=null)
                q.add(curr.left);
                
                if(curr.right!=null)
                q.add(curr.right);
            }
        }
        
        return arr;
    }
}
Leave a Comment