Given the root of an N-ary tree of unique values, and two nodes of the tree
p and q.
You should move the subtree of the node p to become a direct child of node
q. If p is already a direct child of q, do not change anything. Node pmust be the last child in the children list of node q.
Return the root of the tree after adjusting it.
There are 3 cases for nodes p and q:
Node q is in the sub-tree of node p.
Node p is in the sub-tree of node q.
Neither node p is in the sub-tree of node q nor node q is in the sub-tree of node p.
In cases 2 and 3, you just need to move p (with its sub-tree) to be a child of q, but in case 1 the tree may be disconnected, thus you need to reconnect the tree again. Please read the examples carefully before solving this problem.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
For example, the above tree is serialized as
[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].
Input: root =[1,null,2,3,null,4,5,null,6,null,7,8], p =4, q =1Output: [1,null,2,3,4,null,5,null,6,null,7,8]Explanation: This example follows the second case as node p isin the sub-tree of node q. We move node p with its sub-tree to be a direct child of node q.Notice that node 4is the last child of node 1.
Example 2:
1
2
3
4
5
Input: root =[1,null,2,3,null,4,5,null,6,null,7,8], p =7, q =4Output: [1,null,2,3,null,4,5,null,6,null,7,8]Explanation: Node 7is already a direct child of node 4. We don't change anything.
Example 3:
1
2
3
4
5
Input: root =[1,null,2,3,null,4,5,null,6,null,7,8], p =3, q =8Output: [1,null,2,null,4,5,null,7,8,null,null,null,3,null,6]Explanation: This example follows case3 because node p is not in the sub-tree of node q and vice-versa. We can move node 3with its sub-tree and make it as node 8's child.
We need to move the subtree rooted at node p to be the last child of node q. The main challenge is handling the case when q is in the subtree of p, which can disconnect the tree. We use DFS to build parent and node maps, then carefully rewire the tree according to the problem’s cases.