7 lines c++ solution


  • 9
    W

    /*
    The key is to traverse the left subtree with order root -> left -> right,
    and the right subtree with order root -> right-> left
    */

    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        return isSymmetric_helper(root->left, root->right);
    }
    bool isSymmetric_helper(TreeNode* root1, TreeNode* root2) {
        if (root1==NULL && root2==NULL) return true;
        if (root1==NULL || root2==NULL) return false;
        if (root1->val != root2->val) return false;
        return isSymmetric_helper(root1->left, root2->right) && isSymmetric_helper(root1->right, root2->left);
    }

  • 0
    R

    Nice, very neat!


Log in to reply
 

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