[Daily Coding Problem 24] Implement locking in a binary tree. - lz87 - 博客园
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 lockedlock
, 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.
Solution 1.
is_locked(): O(1)
lock(): O(m + h)
unlock(): O(m + h)
lock
and unlock
will take O(m + h) time where m is the number of nodes in the node's subtree (since we have to traverse through all its descendants) and h is the height of the node (since we have to traverse through the node's ancestors).
Read full article from [Daily Coding Problem 24] Implement locking in a binary tree. - lz87 - 博客园
No comments:
Post a Comment