讨论/题目交流/ C 合并二叉树 ,一个思路的细微写法出现错误/
C 合并二叉树 ,一个思路的细微写法出现错误

合并二叉树;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
//重新构建一颗树;

struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2){
             struct TreeNode *p;
             p=(struct TreeNode *)malloc(sizeof(struct TreeNode));
              if(!t1 && !t2)  {    //同时为零时该层递归结束;
                    p=NULL;
                   return NULL;
              }
              if(t1!=NULL && t2==NULL) 
                   p->val=t1->val;
                   
              if(t2!=NULL && t1==NULL) 
                    p->val=t2->val;  

              if(t1&&t2) 
             p->val=t1->val+t2->val;
// 33line;
              p->left=mergeTrees(t1->left,t2->left); 
              p->right=mergeTrees(t1->right ,t2->right); 
              
              return p;  
}

出现error Line 33: Char 23: runtime error: member access within null pointer of type 'struct TreeNode' (solution.c) //使用空指针;
改为



/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
//重新构建一颗树;



struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2){
             struct TreeNode *p;
             p=(struct TreeNode *)malloc(sizeof(struct TreeNode));
              if(!t1 && !t2)  {    //同时为零时该层递归结束;
                    p=NULL;
                   return NULL;
              }
              if(t1!=NULL && t2==NULL) {
                   p->val=t1->val;
                    p->left=mergeTrees(t1->left,NULL); 
                    p->right=mergeTrees(t1->right ,NULL); 
                   
              }
              if(t2!=NULL && t1==NULL) {
                    p->val=t2->val;  
                   p->left=mergeTrees(NULL,t2->left); 
                   p->right=mergeTrees(NULL,t2->right); 
               
              }
              if(t1&&t2) {
                   p->val=t1->val+t2->val;
              p->left=mergeTrees(t1->left,t2->left); 
              p->right=mergeTrees(t1->right ,t2->right); 
              }
              return p;  
}

|617 |合并二叉树|简单|
能够正常通过, 假设 t2==NULL 那t2->left==NULL ,我调用 p->left=mergeTrees(t1->left,NULL); 和 p->left=mergeTrees(t1->left,t2->left); 的意思不是一样的吗??? ,求大神解释一下;

展开讨论
共 0 个讨论
无讨论