C Solution - Swap nodes in place (bitwise)


  • 0
    G

    This approach swap nodes using bitwise.

    #define swap_nodes(a, b)    \
    ({                          \
        a = (((struct TreeNode *) ((uintptr_t) (a) ^ (uintptr_t) (b)))); \
        b = (((struct TreeNode *) ((uintptr_t) (a) ^ (uintptr_t) (b)))); \
        a = (((struct TreeNode *) ((uintptr_t) (a) ^ (uintptr_t) (b)))); \
    })
    
    struct TreeNode* invertTree(struct TreeNode* root) {
        if (!root)
            return NULL;
        
        invertTree(root->left);
        invertTree(root->right);
        
        swap_nodes(root->left, root->right);
        
        return root;
    }
    

Log in to reply
 

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