Move Sub-Tree of N-Ary Tree - Problem

Given the root of an N-ary tree with unique values, and two nodes p and q.

You should move the subtree of 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:

1. Node q is in the sub-tree of node p.

2. Node p is in the sub-tree of node q.

3. 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.

Input & Output

Example 1 — Move Node to Sibling
$ Input: root = [1,2,3,null,4,5,null,null,6,null], p = 2, q = 3
Output: [1,3,null,2,5,null,null,4,null,null,6,null]
💡 Note: Move node 2 and its subtree (including node 4) to become the last child of node 3. Node 3 already has child 5, so node 2 becomes the second child.
Example 2 — q in Subtree of p
$ Input: root = [1,2,3,null,4,5,null,null,6,null], p = 1, q = 2
Output: [2,4,1,null,null,3,null,null,5,null,null,6,null]
💡 Note: Node q=2 is in subtree of p=1. Move p=1 under q=2, and q=2 becomes the new root since original root was moved.
Example 3 — Already Direct Child
$ Input: root = [1,2,3,null,4,5,null], p = 4, q = 2
Output: [1,2,3,null,4,5,null]
💡 Note: Node p=4 is already a direct child of q=2, so no change is needed.

Constraints

  • The total number of nodes is between [2, 1000]
  • Each node has a unique value
  • Node.val == p != Node.val == q
  • p and q are different and both exist in the tree

Visualization

Tap to expand
Move Sub-Tree of N-Ary Tree INPUT TREE 1 2 p 3 q 4 5 6 root=[1,2,3,null,4,5...] p=2, q=3 ALGORITHM STEPS 1 Identify Case Check p,q relationship (Case 3: neither in other) 2 Find Parents DFS to locate p's parent parent(2) = 1 3 Remove p from parent Remove node 2 from node 1's children 4 Attach p to q Add node 2 as last child of node 3 Single Pass DFS 1 --> 1 FINAL RESULT 1 3 q 2 p (moved) 5 4 6 [1,3,null,2,5,null,null, 4,null,null,6,null] OK - Tree Adjusted Key Insight: Single Pass DFS handles all 3 cases efficiently. When q is in p's subtree (Case 1), we must reconnect q's original parent to p's parent to prevent tree disconnection. Time: O(n), Space: O(h) where h is tree height for recursion stack. TutorialsPoint - Move Sub-Tree of N-Ary Tree | Single Pass DFS Approach
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
12.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen