IsSameTree not working


  • 0
    J

    //Why wont this work? Apparently theres a runtime error...

     class Solution{
     public:
     bool isSameTree(TreeNode *p, TreeNode* q) {
          if (p->val == q-> val) {
          return true;
          }
          if (p == NULL && q==NULL) {
          return true;
          }
          if ( p== NULL || q == NULL || p->val != q->val)
          {  
           return false;
          }
    
          return isSameTree(p->left, q->left) && 
                 isSameTree(p->right, q-right);
    
     }
     }

  • 1
    R

    the last line,u mistype a > syntax.

     isSameTree(p->right, q-right);
    

    should be like

    isSameTree(p->right, q->right);
    

    and yr logic is not correct.
    here is my solution, hope u can figure it out. it's not too complex

    bool isSameTree(struct TreeNode *p, struct TreeNode *q) {
        if(NULL==p && NULL==q) return true;
        
    	if(NULL!=p && NULL!=q){
    		if(p->val==q->val &&
    				isSameTree(p->left,q->left) &&
    				isSameTree(p->right,q->right) ){
    			return true;
    		} else {
    			return false;
    		}
    
    	}
    	return false;
    }

Log in to reply
 

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