Accepted: 2 Queue Solution share


  • 0
    D

    '''
    public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
    if(root == null) return new ArrayList<Integer> ();
    Queue<TreeNode> q1 = new LinkedList<>();
    Queue<TreeNode> q2 = new LinkedList<>();
    List<Integer> list = new ArrayList<>();

        q1.offer(root);
        while(!q1.isEmpty() || !q2.isEmpty()){
            while(!q1.isEmpty()){
                root = q1.poll();
                if(q1.isEmpty())
                    list.add(root.val);
                if(root.left != null) q2.offer(root.left) ;
                if(root.right != null) q2.offer(root.right) ;
            }
            while(!q2.isEmpty()){
                root = q2.poll();
                if(q2.isEmpty())
                    list.add(root.val);
                if(root.left != null) q1.offer(root.left) ;
                if(root.right != null) q1.offer(root.right) ;
            }
        }
        
        return list;
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.