Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

156. Binary Tree Upside Down

Explanation:

The problem asks us to flip a binary tree upside down. The idea is to perform a bottom-up traversal of the tree and modify the nodes accordingly. At each step, we set the right child of the current node as the left child of the next node and the left child of the current node as the right child of the next node. We continue this process until we reach the leftmost node, which becomes the new root of the upside-down tree.

Algorithm:

  1. If the root is null or it has no left child, return the root.
  2. Recursively traverse to the leftmost node (newRoot) by calling the function on the left child.
  3. Set the left child of the leftmost node (newRoot) to the right child of the root.
  4. Set the right child of the leftmost node (newRoot) to the root.
  5. Set the left and right child of the root as null.
  6. Return the newRoot as the root of the upside-down tree.

Time Complexity:

The time complexity of this approach is O(n) where n is the number of nodes in the binary tree.

Space Complexity:

The space complexity is O(h) where h is the height of the binary tree, due to the recursive calls on the stack.

: :

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.