HardNo. 1516LeetCode Premium

Move Sub-Tree of N-Ary Tree — LeetCode 1516 Python Solution

Topics
Tree, Depth-First Search
Reading time
2 min

The problem

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.

Example

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.

Complexity

Time
O(V+E)
Space · auxiliary
O(V)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1516. Move Sub-Tree of N-Ary Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0098Validate Binary Search TreeMedium
0099Recover Binary Search TreeMedium
0100Same TreeEasy
0101Symmetric TreeEasy
0104Maximum Depth of Binary TreeEasy
0110Balanced Binary TreeEasy

Frequently asked questions

How hard is LeetCode 1516. Move Sub-Tree of N-Ary Tree?

LeetCode 1516. Move Sub-Tree of N-Ary Tree is rated Hard on LeetCode.

What is the time complexity of LeetCode 1516. Move Sub-Tree of N-Ary Tree?

The Python solution on this page runs in O(V+E).

What is the space complexity of LeetCode 1516. Move Sub-Tree of N-Ary Tree?

The Python solution on this page uses O(V) auxiliary space.

What topics does LeetCode 1516. Move Sub-Tree of N-Ary Tree cover?

LeetCode 1516. Move Sub-Tree of N-Ary Tree is tagged Tree and Depth-First Search on LeetCode.

Is LeetCode 1516. Move Sub-Tree of N-Ary Tree a premium problem?

Yes. LeetCode 1516. Move Sub-Tree of N-Ary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.