Magicsheet logo

Move Sub-Tree of N-Ary Tree

Hard
25%
Updated 8/1/2025

Asked by 1 Company

Move Sub-Tree of N-Ary Tree

What is this problem about?

The Move Sub-Tree of N-Ary Tree problem gives you an N-ary tree (each node can have multiple children) and two node references p and q. Move the subtree rooted at p to become a child of q. If p is already a child of q, move it to be the last child. This hard Move Sub-Tree of N-Ary Tree coding problem requires careful parent tracking and edge cases around ancestor-descendant relationships.

Why is this asked in interviews?

Google asks this hard problem to test DFS on N-ary trees combined with edge case reasoning. The tricky case — when q is a descendant of p — requires detaching p from its parent first, then re-attaching. The depth-first search and tree interview pattern is the core, and the problem tests whether candidates can reason carefully about tree structure changes without corrupting the tree.

Algorithmic pattern used

DFS for parent finding + careful re-attachment. First, find the parent of p and the parent of q using DFS. Handle the edge case: if q is a descendant of p, first detach p from its parent (replacing p in its parent's children list with p's children or handling accordingly), then make q's parent correct. Otherwise, simply detach p from its current parent, then add p as the last child of q.

Example explanation

Tree: root→[A, B, C]. A→[D, E]. Move subtree at A to become child of B.

  • Find parent of A = root. Find parent of B = root.
  • B is not a descendant of A.
  • Remove A from root's children. Add A as last child of B.
  • Tree after: root→[B, C]. B→[A]. A→[D, E].

Edge case: Move root's child B (with B→A) under A. A is a descendant of root but B is parent of A... handle carefully.

Common mistakes candidates make

  • Not handling the case where q is a descendant of p (causes a cycle).
  • Failing to update the parent reference after detachment.
  • Not correctly identifying and removing p from its original parent's children list.
  • Assuming p's parent is always the root (may be deep in the tree).

Interview preparation tip

Tree restructuring problems require clearly separating the "find" phase from the "modify" phase. First, gather all necessary information (parent of p, parent of q, relationship between p and q). Then apply modifications. The ancestor check — "is q a descendant of p?" — is the critical invariant test. Practice DFS parent-tracking implementations on N-ary trees, as they differ slightly from binary tree restructuring in requiring iteration over children lists.

Similar Questions