Change the Root of a Binary Tree — LeetCode 1666 Python Solution
- Problem
- #1666
- Pattern
- Tree Traversal
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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 cur has a left child, then that child becomes cur's right child.
Example
- 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]
Python solution
"""
# 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 leafComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1666. Change the Root of a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1666. Change the Root of a Binary Tree?
- LeetCode 1666. Change the Root of a Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1666. Change the Root of a Binary Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 1666. Change the Root of a Binary Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 1666. Change the Root of a Binary Tree cover?
- LeetCode 1666. Change the Root of a Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
- Is LeetCode 1666. Change the Root of a Binary Tree a premium problem?
- Yes. LeetCode 1666. Change the Root of a Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.