Whats wrong in my code ? Got MLE.


  • 0
    H

    My idea is simple. I am storing right most element in every level by performing level order traversal.

    public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            if(root==null)
            return result;
            Queue<TreeNode> q= new LinkedList<TreeNode>();
            TreeNode dummy= new TreeNode(Integer.MIN_VALUE);
            q.add(root);
            q.add(dummy);
            TreeNode previous=null;
            while(!q.isEmpty())
            {
            	TreeNode current=q.poll();
                if(current!=dummy)
                {
                	previous=current;
                    if(current.left!=null)
                    q.add(current.left);
                    if(current.right!=null)
                    q.add(current.right);
                }
                else
                {
                	result.add(previous.val);
                    if(q.size()!=1)
                	q.add(dummy);
                    else 
                    break;	
                }
            }
            return result;
    

    }


  • 0
    L

    It seems like your dummy element is not added to the linked list q if there is only a single element remaining in the list:

    if(q.size()!=1)
        q.add(dummy);
    

    should read

    if(!q.isEmpty())
        q.add(dummy);

  • 0
    H

    Thanks man. I spent some time to figure out this bug.


Log in to reply
 

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