Recursion, a natural thought:

LeetCode "Binary Tree Upside Down"_ideLeetCode "Binary Tree Upside Down"_学习_02
class Solution 
{
    //    Top : BottomRight
    std::pair<TreeNode *, TreeNode *> rotate(TreeNode *p)
    {
        if (!p->left && !p->right)
        {
            return make_pair(p, p);
        }

        auto r = rotate(p->left);
        r.second->left = p->right;
        r.second->right = p;
        
        if (p->right)
            p->right->left = p->right->right = nullptr;
        p->left = p->right = nullptr;
        
        return make_pair(r.first, p);
    }
public:
    TreeNode* upsideDownBinaryTree(TreeNode* root) 
    {
        if (!root) return root;
        auto r = rotate(root);
        return r.first;
    }
};
View Code

Iterative, just picture it in your mind :)

LeetCode "Binary Tree Upside Down"_ideLeetCode "Binary Tree Upside Down"_学习_02
class Solution 
{
public:
    TreeNode* upsideDownBinaryTree(TreeNode* root) 
    {
        TreeNode *cur = root, *p = nullptr, *pr = nullptr;
        while(cur)
        {
            // Rotate
            auto left = cur->left; // store
            cur->left = pr;
            pr = cur->right; // move on
            cur->right= p;
            
            // Move on left-wards
            p = cur;
            cur = left;
        }
        return p;
    }
};
View Code