0ms C++ solution


  • 0
    C
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p && q) {
            return  (p->val== q->val &&
                     isSameTree(p->left, q->left) &&
                     isSameTree(p->right, q->right) ) ;
        }
        return !p && !q;
    }
    

    It would be interesting to note that the order of the conditions in the expression. By having the test

    p->val== q->val
    

    as the first condition on the expression. We are able to stop evaluating the sub-trees if the values are different. If the above condition is false the && expression short-circuits and won't evaluate the twoSubTrees. Same holds if any of the subTrees are not equal (the other won't be evaluated).


Log in to reply
 

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