C++ with recursion and a little faster

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

    Here is my solution with recursion, while a little bit faster than the one with less lines.
    I have no idea why it would be faster if I use two if statement than just use one, but it dose.

Log in to reply

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