Operations on Tree Problem
#1993
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1993.
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the i^th node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
- Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
- Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
- Upgrade: Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true:
- The node is unlocked,
- It has at least one locked descendant (by any user), and
- It does not have any locked ancestors.
Implement the LockingTree class:
LockingTree(int[] parent)initializes the data structure with the parent array.lock(int num, int user)returnstrueif it is possible for the user with iduserto lock the nodenum, orfalseotherwise. If it is possible, the nodenumwill become locked by the user with iduser.unlock(int num, int user)returnstrueif it is possible for the user with iduserto unlock the nodenum, orfalseotherwise. If it is possible, the nodenumwill become unlocked.upgrade(int num, int user)returnstrueif it is possible for the user with iduserto upgrade the nodenum, orfalseotherwise. If it is possible, the nodenumwill be upgraded.
Example 1:

Input
["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"]
[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]
Output
[null, true, false, true, true, true, false]
Explanation
LockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
Constraints:
n == parent.length2 <= n <= 20000 <= parent[i] <= n - 1fori != 0parent[0] == -10 <= num <= n - 11 <= user <= 10^4parentrepresents a valid tree.- At most
2000calls in total will be made tolock,unlock, andupgrade.
Solution
Approach: Simulation
Store for each node the user who locked it (or -1) and the list of its children.
lockandunlockonly check and change the node's own entry.upgradefirst walks up from the node to the root: if the node or any ancestor is locked, returnfalse. Then it runs a DFS over the subtree, unlocking every locked descendant and remembering whether it found one. If none was found, returnfalse(nothing changes); otherwise lock the node for the user and returntrue.
Complexity: lock and unlock take O(1); upgrade takes O(n), so q calls take O(q * n). Space O(n).
class LockingTree:
def __init__(self, parent: List[int]):
n = len(parent)
self.locked = [-1] * n
self.parent = parent
self.children = [[] for _ in range(n)]
for son, fa in enumerate(parent[1:], 1):
self.children[fa].append(son)
def lock(self, num: int, user: int) -> bool:
if self.locked[num] == -1:
self.locked[num] = user
return True
return False
def unlock(self, num: int, user: int) -> bool:
if self.locked[num] == user:
self.locked[num] = -1
return True
return False
def upgrade(self, num: int, user: int) -> bool:
def dfs(x: int):
nonlocal find
for y in self.children[x]:
if self.locked[y] != -1:
self.locked[y] = -1
find = True
dfs(y)
x = num
while x != -1:
if self.locked[x] != -1:
return False
x = self.parent[x]
find = False
dfs(num)
if not find:
return False
self.locked[num] = user
return True
# Your LockingTree object will be instantiated and called as such:
# obj = LockingTree(parent)
# param_1 = obj.lock(num,user)
# param_2 = obj.unlock(num,user)
# param_3 = obj.upgrade(num,user)