Simple C++ solution adapted from two related problems


  • 0
    K

    This code is adapted from two best solutions in related problem (invert binary tree, same tree), if you understand them well, this should be very easy. The basic idea is to invert the right half of the tree then compare two sides. The running time is 4ms.

    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if(root==NULL){return true;}
            return isSameTree(root->left,root->right);
        }
    private:
        bool isSameTree(TreeNode* p, TreeNode* q) {
           if (p == NULL || q == NULL) return (p == q); 
           swap(q->left,q->right);
           return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
        }
    };

Log in to reply
 

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