1516. Move Sub-Tree of N-Ary Tree
https://leetcode.com/problems/move-sub-tree-of-n-ary-tree
Description
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, don't 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:

Example 2:

Example 3:

Example 4:

Example 5:

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).
ac
Last updated
Was this helpful?