Binary Tree Upside Down

medium tree dfs binary tree

Problem

Given a binary tree where every right child has a sibling left child and no children of its own, flip it upside down. The leftmost leaf becomes the new root, the original right child becomes its left, and the original parent becomes its right.

Inputlevels = [1, 2, 3, 4, 5]
Output[4, 5, 2, null, null, 3, 1]
Node 4 is the leftmost leaf and becomes the new root; 5 → left, 2 → right; 3 hangs off 2 as left, 1 as right.

def upside_down_binary_tree(root):
    if root is None or root.left is None:
        return root
    new_root = upside_down_binary_tree(root.left)
    root.left.left = root.right
    root.left.right = root
    root.left = None
    root.right = None
    return new_root
function upsideDownBinaryTree(root) {
  if (root === null || root.left === null) return root;
  const newRoot = upsideDownBinaryTree(root.left);
  root.left.left = root.right;
  root.left.right = root;
  root.left = null;
  root.right = null;
  return newRoot;
}
class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if (root == null || root.left == null) return root;
        TreeNode newRoot = upsideDownBinaryTree(root.left);
        root.left.left = root.right;
        root.left.right = root;
        root.left = null;
        root.right = null;
        return newRoot;
    }
}
TreeNode* upsideDownBinaryTree(TreeNode* root) {
    if (root == nullptr || root->left == nullptr) return root;
    TreeNode* newRoot = upsideDownBinaryTree(root->left);
    root->left->left = root->right;
    root->left->right = root;
    root->left = nullptr;
    root->right = nullptr;
    return newRoot;
}
Time: O(n) Space: O(n) recursion