903. Move Sub-Tree of N-Ary Tree

Given the root of an N-ary tree, where each node has a unique value, and two distinct nodes p and q, you must modify the tree structure by moving the entire subtree rooted at p to become a direct child of q. If p is already a direct child of q, the tree remains unchanged. Additionally, p must always be the last child in q's list of children.

The following scenarios must be handled:

  • If q is in the subtree of p: Moving p under q may disconnect the tree. In this case, you need to properly reconnect the remaining part of the tree to ensure it remains valid.
  • If p is in the subtree of q: The structure remains mostly unchanged, and p should simply be moved under q as its last child.
  • If neither p nor q is in each other's subtree: The subtree rooted at p is detached and reattached under q without requiring additional reconnections.

The tree is represented using level-order traversal, where each group of children is separated by null.

Example 1:

Input: root = [10,null,20,30,null,40,50,null,60,null,70,80], p = 40, q = 10

Output: [10,null,20,30,40,null,50,null,60,null,70,80]

Explanation: Since p (40) is in the subtree of q (10), we move 40 (along with its subtree) directly under 10, ensuring it is the last child of 10.

Example 2:

Input: root = [10,null,20,30,null,40,50,null,60,null,70,80], p = 70, q = 40

Output: [10,null,20,30,null,40,50,null,60,null,70,80]

Explanation: Since p (70) is already a direct child of q (40), no modifications are made to the tree.

Now Your Turn!

Pick the correct output for the given input

Input: root = [10,null,20,30,null,40,50,null,60,null,70,80], p = 30, q = 80

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [2, 1000].
  • Each node has a unique value.
  • Both p and q are guaranteed to be present in the tree.
  • p ≠ q.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for an n-ary tree node.
* class TreeNode {
* public:
* int val;
* vector<TreeNode*> children;
*
* TreeNode() {}
*
* TreeNode(int _val) {
* val = _val;
* }
*
* TreeNode(int _val, vector<TreeNode*> _children) {
* val = _val;
* children = _children;
* }
* };
**/
 
class Solution {
public:
TreeNode* moveSubTree(TreeNode* root, TreeNode* p, TreeNode* q) {
}
};
Test Case

Input:

P
Q
Root