697. Change the Root of a Binary Tree

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.
  • cur's original parent becomes cur's left child. Note that in this process the original parent's pointer to cur becomes null, making it have at most one child.

Return the new root of the re-rooted tree and ensure that your solution sets the Node.parent pointers correctly after re-rooting.

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]

Explanation: The given leaf node (7) becomes the new root, and its path to the original root (3) is reversed to maintain the tree structure.

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]

Explanation: The given leaf node (0) becomes the new root, and its path to the original root (3) is reversed to maintain the tree structure.

Now Your Turn!

Pick the correct output for the given input

Input: root = [10,7,15,5,8,12,18,null,null,null,null,11,14], leaf = 11

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [2, 100].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • leaf exists in the tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/*
// Definition for a Node.
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
TreeNode* parent;
};
*/
 
class Solution {
public:
TreeNode* flipBinaryTree(TreeNode* root, TreeNode * leaf) {
}
};
Test Case

Input:

Leaf
Root