[LeetCode] Change the Root of a Binary Tree

1666. 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:

  1. If cur has a left child, then that child becomes cur’s right child.
  2. 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 rerooted tree.

Note: Ensure that your solution sets the Node.parent pointers correctly after rerooting or you will receive “Wrong Answer”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* parent;
};
*/

class Solution {
void unlink(Node* child, Node* par) {
if(child->left == par) child->left = nullptr;
if(child->right == par) child->right = nullptr;
}
public:
Node* flipBinaryTree(Node* root, Node * leaf) {
Node* res = leaf;
Node* child = leaf->parent, *par = leaf;
while(par != root) {
if(par->left) swap(par->left, par->right);
Node* nchild = child->parent;
unlink(child, par);
par->left = child;
child->parent = par;
par = child;
child = nchild;
}
res->parent = nullptr;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/01/PS/LeetCode/change-the-root-of-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.