The Locking Tree Problem involves implementing a set of locking operations on nodes within an M-ary tree. Each node in the tree can be "locked" or "unlocked" by a user, with constraints on how and when nodes can be locked or unlocked, depending on their relationship within the tree.
This project defines three primary operations:
- Lock - Lock a specific node.
- Unlock - Unlock a previously locked node.
- UpgradeLock - Upgrade the lock on a node to include its ancestors if certain conditions are met.
You have a hierarchical world map represented as an M-ary tree, resembling the structure below:
You need to define three operations on this tree structure:
lock(X, uid)
: Locks nodeX
for useruid
.unlock(X, uid)
: Unlocks nodeX
if it was locked by the same user.upgradeLock(X, uid)
: Upgrades the lock on nodeX
to an ancestor lock if all locked descendants are locked byuid
.
-
Lock(X, uid):
- Grants exclusive access to the subtree rooted at
X
for the useruid
. - After a successful lock on
X
:lock(A, anyUserId)
will fail ifA
is a descendant ofX
.lock(B, anyUserId)
will fail ifX
is a descendant ofB
.
- Locking a node that is already locked will fail.
- Grants exclusive access to the subtree rooted at
-
Unlock(X, uid):
- Unlocks the node
X
if it was previously locked by the same useruid
. - Returns
true
if the unlock is successful.
- Unlocks the node
-
UpgradeLock(X, uid):
- Upgrades the lock on node
X
if:- All descendants of
X
that are locked are locked by the sameuid
.
- All descendants of
- Upgrade fails if any locked descendant of
X
is locked by a different user. - Once
UpgradeLock
onX
succeeds,X
is considered locked byuid
.
- Upgrades the lock on node
- Header Files: Contains tree structure definitions, operations, and helper functions.
- Source Code: Implements the locking logic, including conditions for each operation.
- Example Scenarios: Example test cases to validate each operation and edge cases.
To compile and run the project, use the following command in your terminal:
g++ -o locking_tree locking_tree.cpp -std=c++11
./locking_tree