Accepted C++ solution by swapping left/right of one branch


  • 0
    K
    void swap(TreeNode *root) {
        if (NULL == root) return;
        
        swap(root->left);
        swap(root->right);
        
        TreeNode *tmp;
        tmp = root->left;
        root->left = root->right;
        root->right = tmp;
    }
    
    bool compare(TreeNode *a, TreeNode *b) {
        if (NULL == a && NULL == b) return true;
        if (NULL == a || NULL == b) return false;
        
        if (a->val == b->val) {
            return (compare(a->left, b->left) && compare(a->right, b->right));
        } else {
            return false;
        }
    }
    
    bool isSymmetric(TreeNode *root) {
        if (NULL == root) return true;
        swap(root->left);
        return compare(root->left, root->right);
    }

Log in to reply
 

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