Move Sub-Tree of N-Ary Tree Problem
Description
LeetCode Problem 1516.
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 p must 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
qis in the sub-tree of nodep. - Node
pis in the sub-tree of nodeq. - Neither node
pis in the sub-tree of nodeqnor nodeqis in the sub-tree of nodep.
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].
Example 1:

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 4, q = 1
Output: [1,null,2,3,4,null,5,null,6,null,7,8]
Explanation: This example follows the second case as node p is in 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 4 is the last child of node 1.
Example 2:

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 7, q = 4
Output: [1,null,2,3,null,4,5,null,6,null,7,8]
Explanation: Node 7 is already a direct child of node 4. We don't change anything.
Example 3:

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 3, q = 8
Output: [1,null,2,null,4,5,null,7,8,null,null,null,3,null,6]
Explanation: This example follows case 3 because node p is not in the sub-tree of node q and vice-versa. We can move node 3 with its sub-tree and make it as node 8's child.
Example 4:

Input: root = [1,null,2,3,null,4], p = 1, q = 4
Output: [4,null,1,null,2,3]
Explanation: This example follows case 1 because node q is in the sub-tree of node p. Disconnect 4 with its parent and move node 1 with its sub-tree and make it as node 4's child.
Constraints:
- The total number of nodes is between
[2, 1000]. - Each node has a unique value.
p != nullq != nullpandqare two different nodes (i.e.p != q).
Solution
Approach: Parent Map and Three Cases
Moving a subtree is just cutting one child pointer and adding another, as long as we know each node's parent. So first walk the tree once and record parent[node] for every node (the root has none).
Then handle the cases from the statement:
pis already a child ofq(parent[p] == q): return the tree unchanged. Without this check we would movepto the end ofq's children, which changes the order.qis inp's subtree (case 1): walk up fromqthrough the parents; if we meetp, this is the case. Cuttingpout alone would also carryqaway, and attachingpunderqwould create a cycle. So first cutqout of its parent's children, then putqexactly wherepwas inp's parent's children list (same position). Ifpwas the root,qbecomes the new root. Finally appendptoq's children.- Otherwise (cases 2 and 3): remove
pfrom its parent's children and append it toq's children. Herepcannot be the root, because every node is in the root's subtree.
Note that in case 1 q's parent may be p itself. That still works: q leaves p's children, takes p's place, and p (with its remaining children) hangs under q.
Complexity: O(n) time for the parent walk and the list updates, and O(n) space for the parent map.
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children if children is not None else []
"""
class Solution:
def moveSubTree(self, root: 'Node', p: 'Node', q: 'Node') -> 'Node':
# Record every node's parent.
parent = {root: None}
stack = [root]
while stack:
node = stack.pop()
for child in node.children:
parent[child] = node
stack.append(child)
if parent[p] is q:
return root # already a direct child of q
# Is q inside p's subtree? Walk up from q.
node = q
while node is not None and node is not p:
node = parent[node]
if node is p:
# Case 1: cut q out, and put it where p was (q may become the root).
parent[q].children.remove(q)
above = parent[p]
if above is None:
root = q
else:
above.children[above.children.index(p)] = q
else:
# Cases 2 and 3: just cut p out.
parent[p].children.remove(p)
q.children.append(p)
return root