A simple C++ Recursive Solution


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

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

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

    }


Log in to reply
 

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