Compare commits
5 commits
691cf704f4
...
42910bca86
Author | SHA1 | Date | |
---|---|---|---|
|
42910bca86 | ||
|
36cb7e080f | ||
|
6d292a3978 | ||
|
7cbbdcad06 | ||
|
d89ea56edd |
|
@ -48,29 +48,27 @@ Splitting a tree means taking a key, and getting the following output:
|
|||
```python
|
||||
type OptionalNode[K, V] = Node[K, V] | None
|
||||
|
||||
class SplitResult(NamedTuple):
|
||||
left: OptionalNode
|
||||
node: OptionalNode
|
||||
right: OptionalNode
|
||||
|
||||
def split(root: OptionalNode[K, V], key: K) -> SplitResult:
|
||||
def split(
|
||||
root: OptionalNode[K, V],
|
||||
key: K,
|
||||
) -> tuple[OptionalNode[K, V], OptionalNode[K, V], OptionalNode[K, V]]:
|
||||
# Base case, empty tree
|
||||
if root is None:
|
||||
return SplitResult(None, None, None)
|
||||
return 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 SplitResult(left, root, right)
|
||||
return 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 SplitResult(root, node, right)
|
||||
return root, node, right
|
||||
if key < root.key:
|
||||
left, node, right = split(root.left, key)
|
||||
root.left = right
|
||||
return SplitResult(left, node, root)
|
||||
return left, node, root
|
||||
raise RuntimeError("Unreachable")
|
||||
```
|
||||
|
||||
|
|
Loading…
Reference in a new issue