Can any body please tell me what's missing in my code to handle if a tree contains null nodes ?


  • 2
    N
    public boolean isSameTree(TreeNode p, TreeNode q)
    
    {
    
      boolean b = false;
         
      if (p == null && q == null)
        {
            return true;
        }
      
    if(p != null && q != null &&  p.val == q.val)
        {
            b=true;
            if(p.left != null && q.left != null && p.left.val == q.left.val)
            {
    
     b=true;            
    
    isSameTree(p.left,q.left);
                
            }
             
           if(p.right != null && q.right != null && p.right.val == q.right.val)
            {
              b=true;
                isSameTree(p.right,q.right);
             
            }
           
            
        }
        else
            {
                b=false;
            }
        return b;
    }

  • 0
    V

    We usually check if either of tree has NULL nodes like

    if (p == NULL || q == NULL)
    

    Also no need to check for so many conditions. If one node is checked, then every other node is again treated as a new node and so the same method can be called by recursion.

    Something like..

    If either  p==NULL or q == NULL return false;both are NULL return true
    else return (p.val == q.val)&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);

Log in to reply
 

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