Operations on Tree
specialist · 955 · lc medium +32 · 45.1% accepted · 518 likes · top 28%
Description
A tree with n nodes (labeled 0 to n - 1) is described by a parent array where parent[i] is node i's parent and parent[0] = -1 (node 0 is the root). Design a data structure supporting three operations on nodes:
- **Lock**: Lock node num for user only when it is currently unlocked.
- **Unlock**: Unlock node num only when it is locked by user.
- **Upgrade**: Lock node num for user, releasing all its locked descendants, but only when the node is unlocked, has at least one locked descendant, and none of its ancestors are locked.
Implement the LockingTree class with:
- LockingTree(int[] parent) — builds the structure from the parent array.
- lock(int num, int user) — attempts to lock; returns true on success.
- unlock(int num, int user) — attempts to unlock; returns true on success.
- upgrade(int num, int user) — attempts to upgrade; returns true on success.
Example 1:
Example 2:
Code