Where is wrong of my code


  • 0
    J

    public int maxDepth(TreeNode root) {

    List item

    	 LinkedList<TreeNode>queue=new LinkedList<TreeNode>();
    	 TreeNode p;
    	 if(root==null) return 0;
    	 int height=1;
    	 queue.add(root);
    	 while(queue!=null)
    	 {
    		 p=queue.getFirst();
    		 p.val=height;
    		 if(p.left!=null||p.right!=null)
    		 {
    			 height++;
    		 }
    		 if(p.left!=null)
    		 {
    			 queue.add(p.left);
    			 p.left.val=height;
    		 }
    		 else if(p.right!=null)
    		 {
    			queue.add(p.right);
    			p.right.val=height;
    		 }
    		 queue.removeFirst();
    		 
    	 }
    	 return height;
    

    }
    }


  • 0
    V

    In the above program NoSuchElementException is thrown by the LinkedList object as an attempt is made to access the element in an empty LinkedList. While loop condition need to be changed, in the above code queue!=null checks whether the queue object instance is null, in this problem one must check whether the queue is empty or not that can be achieved by using the !queue.isEmpty().

    public class Solution {
        public int maxDepth(TreeNode root) {
            
         LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
         TreeNode p;
         if(root==null) return 0;
         int height=1;
         queue.add(root);
         while(!queue.isEmpty())
         {
             p=queue.getFirst();
             p.val=height;
             if(p.left!=null||p.right!=null)
             {
                 height++;
             }
             if(p.left!=null)
             {
                 queue.add(p.left);
                 p.left.val=height;
             }
             else if(p.right!=null)
             {
                queue.add(p.right);
                p.right.val=height;
             }
             queue.removeFirst();
         }
         return height;
    } 
        
    }

Log in to reply
 

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