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 nodeXfor useruid.unlock(X, uid): Unlocks nodeXif it was locked by the same user.upgradeLock(X, uid): Upgrades the lock on nodeXto an ancestor lock if all locked descendants are locked byuid.
-
Lock(X, uid):
- Grants exclusive access to the subtree rooted at
Xfor the useruid. - After a successful lock on
X:lock(A, anyUserId)will fail ifAis a descendant ofX.lock(B, anyUserId)will fail ifXis 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
Xif it was previously locked by the same useruid. - Returns
trueif the unlock is successful.
- Unlocks the node
-
UpgradeLock(X, uid):
- Upgrades the lock on node
Xif:- All descendants of
Xthat are locked are locked by the sameuid.
- All descendants of
- Upgrade fails if any locked descendant of
Xis locked by a different user. - Once
UpgradeLockonXsucceeds,Xis 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