Skip to content

Instantly share code, notes, and snippets.

@ddunkin
Last active December 21, 2018 04:07
Show Gist options
  • Save ddunkin/eedef74fea055e39087699014f0d1c8b to your computer and use it in GitHub Desktop.
Save ddunkin/eedef74fea055e39087699014f0d1c8b to your computer and use it in GitHub Desktop.
/*
Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked.
Design a binary tree node class with the following methods:
is_locked, which returns whether the node is locked
lock, which attempts to lock the node. If it cannot be locked, then it should return false. Otherwise, it should lock it and return true.
unlock, which unlocks the node. If it cannot be unlocked, then it should return false. Otherwise, it should unlock it and return true.
You may augment the node to add parent pointers or any other property you would like. You may assume the class is used in a single-threaded program, so there is no need for actual locks or mutexes. Each method should run in O(h), where h is the height of the tree
*/
class TreeNode {
parent: TreeNode | undefined;
left: TreeNode | undefined;
right: TreeNode | undefined;
isLocked: boolean;
private isSubtreeLocked: boolean;
lock() {
if (this.isLocked || this.isSubtreeLocked || this.isAncestryLocked()) {
return false;
}
this.isLocked = true;
this.setAncestrySubtreeLocked(true);
return true;
}
unlock() {
if (!this.isLocked || this.isSubtreeLocked || this.isAncestryLocked()) {
return false;
}
this.isLocked = false;
this.setAncestrySubtreeLocked(false);
return true;
}
private isAncestryLocked() {
return this.parent && (this.parent.isLocked || this.parent.isAncestryLocked());
}
private setAncestrySubtreeLocked(isLocked: boolean) {
this.isSubtreeLocked = isLocked;
if (this.parent) {
this.parent.setAncestrySubtreeLocked(isLocked);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment