Binary Tree Upside Down

MediumTreesin-place reversal

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary tree with a special shape: every right child is a leaf, and every right child has a left sibling (a node never has only a right child). Flip the tree upside down and return the new root. The flip works level by level along the leftmost path. For each node on that path that has a left child L: L's new left child becomes the node's original right child, L's new right child becomes the node itself, and the node loses both of its original children. The bottom node of the leftmost path becomes the new root. The tree may be empty, in which case return an empty tree. The result is graded in level order.

Examples

Input: root = [1,2,3]
Output: [2,3,1]
2 becomes the root, with the old right child 3 on its left and the old root 1 on its right.
Input: root = [1,2,3,4,5]
Output: [4,5,2,null,null,3,1]
4 is the new root with children 5 and 2; then 2 takes 3 as its left child and 1 as its right child.
Input: root = []
Output: []
An empty tree stays empty.

Constraints

  • 0 <= number of nodes <= 10
  • 1 <= Node.val <= 10
  • Every right child is a leaf and has a left sibling

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More in-place reversal problems