Change the Root of a Binary Tree Problem
Description
LeetCode Problem 1666.
Given the root of a binary tree and a leaf node, reroot the tree so that the leaf is the new root.
You can reroot the tree with the following steps for each node cur on the path starting from the leaf up to the root excluding the root:
- If
curhas a left child, then that child becomescur's right child. cur's original parent becomescur's left child. Note that in this process the original parent's pointer tocurbecomesnull, making it have at most one child.
Return the new root of the rerooted tree.
Note: Ensure that your solution sets the Node.parent pointers correctly after rerooting or you will receive "Wrong Answer".
Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 7
Output: [7,2,null,5,4,3,6,null,null,null,1,null,null,0,8]
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 0
Output: [0,1,null,3,8,5,null,null,null,6,2,null,null,7,4]
Constraints:
- The number of nodes in the tree is in the range
[2, 100]. -10^9 <= Node.val <= 10^9- All
Node.valare unique. leafexist in the tree.
Solution
Approach: Walk Up From the Leaf
Follow the parent pointers from leaf up to root, rewiring each node cur with its parent p (remember p's own parent gp first):
- If
curhas a left child, move it to becur's right child. - Make
pthe left child ofcurand setp.parent = cur. - Cut the old link from
ptocur(p.leftorp.right, whichever it was).
Then move up: cur = p, p = gp, until cur is the old root. Finally set leaf.parent = null and return leaf as the new root.
Complexity: O(h) time and O(1) space, where h is the depth of leaf.
"""
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
"""
class Solution:
def flipBinaryTree(self, root: "Node", leaf: "Node") -> "Node":
cur = leaf
p = cur.parent
while cur != root:
gp = p.parent
if cur.left:
cur.right = cur.left
cur.left = p
p.parent = cur
if p.left == cur:
p.left = None
elif p.right == cur:
p.right = None
cur = p
p = gp
leaf.parent = None
return leaf