Given the root of a binary tree, turn the tree upside down and return the new root.
You can turn a binary tree upside down with the following steps:
-
The original left child becomes the new root.
-
The original root becomes the new right child.
-
The original right child becomes the new left child.
The steps are done level by level along the left side of the tree, so the deepest node on the leftmost path becomes the root of the result. It is guaranteed that every right node has a sibling (a left node with the same parent) and has no children.
Function Signature
def upside_down_binary_tree(root: Optional[TreeNode]) -> Optional[TreeNode]:
Rules
-
root
is a
TreeNode
with fields
val
,
left
and
right
, or
None
for an empty tree. Return the root of the flipped tree, or
None
when the input is empty.
-
The examples write trees as level-order lists in which
None
marks a missing child and trailing
None
entries are dropped.
-
You may rewire the existing nodes in place. The answer is checked by the shape and values of the returned tree.
Constraints
-
The number of nodes in the tree is in the range
[0, 10]
.
-
1 <= Node.val <= 10
-
Every right node in the tree has a sibling (a left node that shares the same parent) and has no children.
Examples
Input: root = [1,2,3,4,5]
Output: [4,5,2,None,None,3,1]
Node 4, the deepest left node, becomes the root. Its old sibling 5 becomes its left child and its old parent 2 becomes its right child; in turn, 2 takes its old sibling 3 as its left child and its old parent 1 as its right child, and 1 ends up with no children.
Input: root = []
Output: []
An empty tree stays empty.
Input: root = [1,2]
Output: [2,None,1]
Node 2 becomes the root and node 1 becomes its right child. Node 1 had no right child, so node 2 gets no left child.