|
43 | 43 | # AVL TREE
|
44 | 44 | # ---------
|
45 | 45 |
|
| 46 | +""" |
| 47 | + AVLTree{K,V}() |
| 48 | +
|
| 49 | +Construct an empty AVL Tree with keys of type `K` |
| 50 | +and values of type `V`. |
| 51 | +
|
| 52 | + AVLTree() |
| 53 | +
|
| 54 | +Construct an empty AVL Tree that stores keys and values |
| 55 | +of any type, alias for `AVLTree{Any,Any}()`. |
| 56 | +
|
| 57 | +The keys of AVL Tree must implement sorting operators (`>`, `<`) |
| 58 | +and comparison operators (`=`, `≠`) |
| 59 | +
|
| 60 | +# Examples |
| 61 | +
|
| 62 | +```julia |
| 63 | +tree = AVLTree{Int,Float64}() |
| 64 | +
|
| 65 | +# add nodes to the tree |
| 66 | +tree[2] = 2.2 # root node |
| 67 | +tree[1] = 1.1 # left node |
| 68 | +tree[3] = 3.3 # right node |
| 69 | +
|
| 70 | +# update the value of the node |
| 71 | +tree[2] = 2.4 |
| 72 | +
|
| 73 | +# get the value of the node using its key |
| 74 | +tree[2] # 2.4 |
| 75 | +tree[1] # 1.1 |
| 76 | +tree[3] # 3.3 |
| 77 | +
|
| 78 | +# delete nodes from the tree |
| 79 | +delete!(tree, 1) |
| 80 | +delete!(tree, 3) |
| 81 | +``` |
| 82 | +""" |
46 | 83 | mutable struct AVLTree{K,V}
|
47 | 84 | root::Union{AVLNode{K,V},Nothing}
|
48 | 85 | end
|
49 | 86 |
|
50 | 87 | AVLTree{K,V}() where {K,V} = AVLTree{K,V}(nothing)
|
51 | 88 | AVLTree() = AVLTree{Any,Any}()
|
52 | 89 |
|
| 90 | +""" |
| 91 | + getindex(tree::AVLTree{K}, key::K) where {K} |
| 92 | +
|
| 93 | +Get the value stored in the node that has `key`. |
| 94 | +""" |
53 | 95 | function Base.getindex(tree::AVLTree{K}, key::K) where {K}
|
54 | 96 | node = _search(tree, key)
|
55 | 97 | isnothing(node) && throw(KeyError(key))
|
56 | 98 | node.value
|
57 | 99 | end
|
58 | 100 |
|
| 101 | +""" |
| 102 | + setindex!(tree::AVLTree{K}, value, key::K) where {K} |
| 103 | +
|
| 104 | +Add a node to the tree with `key` and `value`. |
| 105 | +If a node with `key` already exists, the value |
| 106 | +of the node will be updated. |
| 107 | +""" |
59 | 108 | function Base.setindex!(tree::AVLTree{K}, value, key::K) where {K}
|
60 | 109 | tree.root = _insert!(tree.root, key, value)
|
61 | 110 | tree
|
62 | 111 | end
|
63 | 112 |
|
| 113 | +""" |
| 114 | + delete!(tree::AVLTree{K}, key::K) where {K} |
| 115 | +
|
| 116 | +Delete the node that has `key` from the tree. |
| 117 | +""" |
64 | 118 | function Base.delete!(tree::AVLTree{K}, key::K) where {K}
|
65 | 119 | tree.root = _delete!(tree.root, key)
|
66 | 120 | tree
|
|
0 commit comments