LeetCode 1666: Change the Root of a Binary Tree
Problem Description
Explanation
To change the root of a binary tree, we can perform a series of operations to rearrange the nodes such that the desired node becomes the new root. The steps involved include finding the path from the desired node to the current root, disconnecting this path, and rearranging the nodes accordingly. We can achieve this using a recursive approach where we traverse the tree to find the path, disconnect the path, and then reattach the nodes to form the new tree.
Algorithmic Steps:
- Find the path from the desired node to the current root using a recursive function.
- Disconnect the path by updating the parent-child relationships along the path.
- Rearrange the nodes to form the new tree with the desired node as the root.
Time Complexity:
The time complexity of this algorithm is O(N) where N is the number of nodes in the binary tree.
Space Complexity:
The space complexity of this algorithm is O(N) due to the recursive function calls.
Solutions
class Solution {
public TreeNode changeRoot(TreeNode root, TreeNode target) {
if(root == null || root == target) {
return root;
}
TreeNode newRoot = findPath(root, target);
return newRoot;
}
private TreeNode findPath(TreeNode node, TreeNode target) {
if(node == null || node == target) {
return node;
}
TreeNode left = findPath(node.left, target);
TreeNode right = findPath(node.right, target);
if(left != null) {
node.left = null;
node.right = left;
return left;
}
if(right != null) {
node.right = null;
node.left = right;
return right;
}
return null;
}
}
Loading editor...