Compare commits
5 commits
42910bca86
...
691cf704f4
| Author | SHA1 | Date | |
|---|---|---|---|
| 691cf704f4 | |||
| aa72b269c2 | |||
| eaaa9c9ae2 | |||
| b3ed39eef3 | |||
| aee1fa55c8 |
1 changed files with 10 additions and 8 deletions
|
|
@ -48,27 +48,29 @@ Splitting a tree means taking a key, and getting the following output:
|
|||
```python
|
||||
type OptionalNode[K, V] = Node[K, V] | None
|
||||
|
||||
def split(
|
||||
root: OptionalNode[K, V],
|
||||
key: K,
|
||||
) -> tuple[OptionalNode[K, V], OptionalNode[K, V], OptionalNode[K, V]]:
|
||||
class SplitResult(NamedTuple):
|
||||
left: OptionalNode
|
||||
node: OptionalNode
|
||||
right: OptionalNode
|
||||
|
||||
def split(root: OptionalNode[K, V], key: K) -> SplitResult:
|
||||
# Base case, empty tree
|
||||
if root is None:
|
||||
return None, None, None
|
||||
return SplitResult(None, None, None)
|
||||
# If we found the key, simply extract left and right
|
||||
if root.key == key:
|
||||
left, right = root.left, root.right
|
||||
root.left, root.right = None, None
|
||||
return left, root, right
|
||||
return SplitResult(left, root, right)
|
||||
# Otherwise, recurse on the corresponding side of the tree
|
||||
if root.key < key:
|
||||
left, node, right = split(root.right, key)
|
||||
root.right = left
|
||||
return root, node, right
|
||||
return SplitResult(root, node, right)
|
||||
if key < root.key:
|
||||
left, node, right = split(root.left, key)
|
||||
root.left = right
|
||||
return left, node, root
|
||||
return SplitResult(left, node, root)
|
||||
raise RuntimeError("Unreachable")
|
||||
```
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue