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 mentioned steps are done level by level. It is guaranteed that every right node has a sibling (a left node with the same parent) and has no children.
The number of nodes in the tree will be 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).
Every right node in the tree has no children.
Solutions
Solution 1
Thinking
Every right child is a leaf with a left sibling, so the tree is a left spine plus right leaves. \(n\le 10\). After the flip the leftmost leaf is the new root, the old root becomes its right child, and the old right child becomes the left. Recurse down the left spine, rewire on the way back, and clear the old root's children.
1 2 3 4 5 6 7 8 910111213141516
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defupsideDownBinaryTree(self,root:Optional[TreeNode])->Optional[TreeNode]:ifrootisNoneorroot.leftisNone:returnrootnew_root=self.upsideDownBinaryTree(root.left)root.left.right=rootroot.left.left=root.rightroot.left=Noneroot.right=Nonereturnnew_root
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcupsideDownBinaryTree(root*TreeNode)*TreeNode{ifroot==nil||root.Left==nil{returnroot}newRoot:=upsideDownBinaryTree(root.Left)root.Left.Right=rootroot.Left.Left=root.Rightroot.Left=nilroot.Right=nilreturnnewRoot}