leetcode:100相同的数

leetcode:100相同的数_第1张图片

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    if(p==NULL&&q==NULL)
        return true;
    if(p==NULL || q == NULL)
        return false;
    if(p->val != q->val)
    {
        return false;
    }
    return isSameTree(p->left,q->left)&&
        isSameTree(p->right,q->right);
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

 bool CompareChild(struct TreeNode* p, struct TreeNode* q)
 { // 判断具有孩子个数和格式是否相同
    if(p==NULL&&q!=NULL)
        return false;
    else if(p!=NULL&&q==NULL)
        return false;
    else if(p->left==NULL&&q->left==NULL)
        return true;
    else if(p->left!=NULL&&q->left!=NULL)
        return true;
    else if(p->right==NULL&&q->right==NULL)
        return true;
    else if(p->right!=NULL&&q->right!=NULL)
        return true;
    else 
        return false ;  
 }
bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    if(p==NULL&&q==NULL)
    return true;
    if(CompareChild(p,q))
    {
        if(p->val == q->val)
        {
            return isSameTree(p->left,q->left)&&
         isSameTree(p->right,q->right);
        }
        else 
            return false;
    }
    else
        return false;
     
}

你可能感兴趣的:(leetcode,java,算法)