Monday, July 18, 2016

AVL Tree implementation

Here is an AVL tree implementation in C++ and Rust. This was probably the easiest self balancing tree I have implemented so far.

C++:


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#pragma once
#include <cmath>
#include <algorithm>
#include <stack>

namespace mds {
    template<
            typename T,
            typename Func = std::less<T>
    >
    class avl_tree {

        struct Node {
            T     key;
            int   h;
            Node *left;
            Node *right;
        };

        Node       *nil;
        Node       *root;
        Func        cmp;
        std::size_t len;

        template<typename ChildA, typename ChildB>
        Node* rotate(Node* n, ChildA childA, ChildB childB) {
            auto new_root    = childA(n);
            childA(n)        = childB(new_root);
            childB(new_root) = n;
            n->h             = compute_h(n);
            new_root->h      = compute_h(new_root);

            return new_root;
        }

        void destroy_tree(Node *n) {
            if (n == nil) {
                return;
            }
            destroy_tree(n->left);
            destroy_tree(n->right);
            delete n;
        }

        template<typename ChildA, typename ChildB>
        Node* tri_node_rotate(Node* x, ChildA childA, ChildB childB) {
            auto c = childA(x);
            if (childA(c)->h < childB(c)->h) {
                childA(x) = rotate(c, childB, childA);
            }
            return rotate(x, childA, childB);
        }

        Node* restructure(Node *n) {
            if (n->left->h > n->right->h) {
                return tri_node_rotate(n, left, right);
            }
            return tri_node_rotate(n, right, left);
        }

        void maintain_invariant(Node *&n) {
            n->h = compute_h(n);
            if (un_balance(n)) {
                n = restructure(n);
            }
        }

        int compute_h(const Node* n) const {
            return 1 + std::max(n->left->h, n->right->h);
        }

        bool un_balance(const Node *x) const {
            return std::abs(x->left->h - x->right->h) > 1;
        }

        template<typename TT>
        void insert_recursive(Node*& n, TT& key) {
            if (n == nil) {
                n = new Node{
                        std::forward<TT>(key),0, nil, nil
                };
                ++len;
            }
            else if (cmp(key, n->key)) {
                insert_recursive(n->left, key);
            }
            else if (cmp(n->key, key)) {
                insert_recursive(n->right, key);
            }
            maintain_invariant(n);
        }

        void remove(Node *&n, const T& key) {
            if (n == nil) {
                return;
            }
            if (cmp(n->key, key)) {
                remove(n->right, key);
            }
            else if (cmp(key, n->key)) {
                remove(n->left, key);
            }
            else if (remove_node(n)) {
                --len;
                return;
            }
            maintain_invariant(n);
        }

        bool remove_node(Node *&n) {
            auto removed = n;
            if (n->left == nil) {
                n = n->right;
            }
            else if (n->right == nil) {
                n = n->left;
            }
            else {
                auto m = min(n->right);
                n->key = m->key;
                remove(n->right, m->key);
                return false;
            }
            delete removed;
            return true;
        }

        Node* min(Node *n) const {
            if (n->left == nil) {
                return n;
            }
            return min(n->left);
        }

        static Node*& left(Node* n) {
            return n->left;
        }
        static Node*& right(Node* n) {
            return n->right;
        }

        template<typename Func>
        void in_order_recursive(Node* n, Func func) const {
            if (n == nil) {
                return;
            }
            in_order_recursive(n->left, func);
            func(n->key);
            in_order_recursive(n->right, func);
        }

    public:

        avl_tree(Func pcmp)
                : nil(new Node{ T(), -1, nullptr, nullptr }),
                  root(nil),
                  cmp(pcmp)
        { }

        avl_tree()
                : avl_tree(Func())
        { }

        avl_tree(std::initializer_list<T> list)
                : avl_tree(Func())
        {
            for (auto e : list) {
                insert(e);
            }
        }

        ~avl_tree() {
            destroy_tree(root);
            delete nil;
        }

        void insert(const T& key) {
            insert_recursive(root, key);
        }
        void insert(T&& key) {
            insert_recursive(root, std::move(key));
        }

        template<typename... Args>
        void emplace(Args&&... args) {
            insert_recursive(root,
                             T(std::forward<Args>(args)...));
        }

        template <typename Func>
        void walk(Func func) const {
            in_order_recursive(root, func);
        }

        void remove(const T &key) {
            remove(root, key);
        }
        std::size_t size() const {
            return len;
        }

        bool contains(const T& key) const {
            auto n = root;
            while (n != nil) {
                if (cmp(n->key, key)) {
                    n = n->right;
                }
                else if (cmp(key, n->key)) {
                    n = n->left;
                }
                else {
                    return true;
                }
            }
            return false;
        }

        class TreeIterator
                : public std::iterator<std::forward_iterator_tag,
                        std::remove_cv_t<T>,
                        std::ptrdiff_t,
                        const T*,
                        const T&>
        {
            using node = Node*;

            node itr;
            node nil;
            std::stack<node> path;

            node find_successor(node n)
            {
                n = n->right;
                if (n != nil)
                {
                    while (n->left != nil)
                    {
                        path.push(n);
                        n = n->left;
                    }
                }
                else
                {
                    n = path.top();
                    path.pop();
                }
                return n;
            }
        public:

            explicit TreeIterator(node n, node pnil) : nil(pnil) //begin
            {
                if (n == nil)
                    itr = nil;
                else
                {
                    path.push(nil);
                    while (n->left != nil)
                    {
                        path.push(n);
                        n = n->left;
                    }
                    itr = n;
                }
            }
            explicit TreeIterator(node pnil) // end
                    : itr(pnil), nil(pnil)
            { }


            TreeIterator& operator++ ()
            {
                itr = find_successor(itr);
                return *this;
            }
            TreeIterator operator++ (int)
            {
                TreeIterator tmp(*this);
                itr = find_successor(itr);
                return tmp;
            }

            bool operator == (const TreeIterator& rhs) const
            {
                return itr == rhs.itr;
            }

            bool operator != (const TreeIterator& rhs) const
            {
                return itr != rhs.itr;
            }

            const T& operator* () const
            {
                return itr->key;
            }

            const T& operator-> () const
            {
                return itr->key;
            }

        };


        using const_iterator = TreeIterator;
        const_iterator begin() const
        {
            return const_iterator(root, nil);
        }
        const_iterator end() const
        {
            return const_iterator(nil);
        }

    };
}


Rust:


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
pub mod set {
    
    use ::std::cmp;
    use ::std::cmp::Ordering::{Less, Greater, Equal};
    use ::std::mem;
    
    pub struct AvlTree<T : Ord> {
        root : Option<Box<Node<T>>>
    }

    struct Node<T : Ord> {
        key    : T,
        height : i32,
        left   : AvlTree<T>,
        right  : AvlTree<T>,
    }

    impl<T> Node<T> where T : Ord{
        fn new(key: T) -> Option<Box<Node<T>>>{
            Some(Box::new(
                    Node { 
                        key    : key, 
                        height : 0, 
                        left   : AvlTree::new(), 
                        right  : AvlTree::new() 
                    }
            )) 
        }    
    }

    impl<T> AvlTree<T>  where T : Ord{    
        
        pub fn new() -> AvlTree<T> {
            AvlTree { root: None }
        }
    
        fn rotate<CA, CB>(&mut self, ch_a: &CA, ch_b: &CB) 
        where CA: Fn(&mut Box<Node<T>>) -> &mut AvlTree<T>,
              CB: Fn(&mut Box<Node<T>>) -> &mut AvlTree<T> {
              
            let mut root          = self.node_take();                                
            let mut child         = ch_a(&mut root).node_take();                                                       
            ch_a(&mut root).root  = ch_b(&mut child).root.take();
            ch_b(&mut child).root = Some(root);
        
            ch_b(&mut child).update_height();
            self.root = Some(child);
            self.update_height();
        }
          
        fn double_rotate<CA, CB>(&mut self, ch_a: &CA, ch_b: &CB) 
        where CA: Fn(&mut Box<Node<T>>) -> &mut AvlTree<T>,
              CB: Fn(&mut Box<Node<T>>) -> &mut AvlTree<T> {
            {
                let child = ch_b(self.m_box());
                if ch_b(child.m_box()).h() < ch_a(child.m_box()).h() {
                    child.rotate(ch_a, ch_b);
                }
            }                   
            self.rotate(ch_b, ch_a);    
        }
    
        fn restructure(& mut self) {                          
            self.update_height();
            let ord = self.root.as_ref()
                          .map(|_| self.degree())
                          .map(|d| (d, d.cmp(&0)));                           
            match ord {
                Some((d, Less))  if -1 > d  => {  
                    self.double_rotate(
                        &|x| &mut x.left, 
                        &|x| &mut x.right)
                },
                Some((d, Greater)) if d > 1 => {
                    self.double_rotate(
                        &|x| &mut x.right, 
                        &|x| &mut x.left)
                },
                _ => { },
            }
        }      
                
        fn update_height(&mut self) {
            self.root.as_mut()
                .map(|r| r.height = cmp::max(r.right.h(), r.left.h()) + 1);
        } 
    
        fn m_box(&mut self) -> &mut Box<Node<T>> {
            self.root.as_mut().expect("root can't be None")
        }
    
        fn r_box(&self) -> & Box<Node<T>> {
            self.root.as_ref().expect("root can't be None")
        }
    
        fn node_take(&mut self) -> Box<Node<T>> {
            self.root.take().expect("root can't be None")
        }
        
        fn h(&self) -> i32 {
            self.root.as_ref().map_or(-1, |x| x.height)
        }
    
        fn degree(&self) -> i32 {
            self.root
                .as_ref()
                .map(|x| x.left.h() - x.right.h())
                .unwrap_or(0)
        }
    
        pub fn insert(&mut self, key : T) {    
            match self.map_to_ord(&key) {
                Some(Less)    => self.m_box().left.insert(key),
                Some(Greater) => self.m_box().right.insert(key),
                None          => self.root = Node::new(key),
                _             => return,
            }
            self.restructure();        
        }
    
        pub fn remove(&mut self, key: &T) {        
            match self.map_to_ord(key) {
                Some(Less)    => self.m_box().left.remove(key),
                Some(Greater) => self.m_box().right.remove(key),
                Some(Equal)   => self.remove_self(key),
                None          => return,

            };
            self.restructure();            
        }
    
        fn min(&mut self) -> &mut Box<Node<T>> {
            let n = self.m_box();
            if n.left.root.is_none(){
                return n; 
            }
            n.left.min()    
        }
    
        fn map_to_ord(&self, key: &T) -> Option<cmp::Ordering> {
            self.root.as_ref()
                .map(|p| &p.key)
                .map(|k| key.cmp(k))
        }
    
        pub fn contains(& self, key: &T) -> bool {        
            match self.map_to_ord(key) {
                Some(Less)    => self.r_box().left.contains(key),
                Some(Greater) => self.r_box().right.contains(key),
                Some(Equal)   => true,
                None          => false,
            }               
        }
    
        fn remove_self(&mut self, key: &T) {            
            let mut c = self.node_take();
            self.root = match (c.left.root.take(), 
                               c.right.root.take()) {
            
                (None, right) => right,        
                (left, None)  =>  left,                        
                (l@ Some(_), r@ Some(_)) => {
                    let mut right = AvlTree{root: r};
                    mem::swap(
                        &mut right.min().key, 
                        &mut c.key);
                
                    c.right     = right;
                    c.left.root = l;
                    c.right.remove(key);
                    Some(c)
                }
            };
        }
        
        pub fn iter<'a>(&'a self) -> TreeIterator<'a, T> {
            TreeIterator { 
                current : self.root.as_ref(),
                path: Vec::new(),
            }    
        }
    }
    
    pub struct TreeIterator<'a, T: 'a> where T: Ord {
        current : Option<&'a Box<Node<T>>>,
        path: Vec<&'a Box<Node<T>>>,
    }

    impl<'a, T> IntoIterator for & 'a AvlTree<T> where T: Ord {
        type Item = &'a T;
        type IntoIter = TreeIterator<'a, T>;
        fn into_iter(self) -> Self::IntoIter {
            self.iter()
        }
    }

    impl<'a, T> Iterator for TreeIterator<'a, T> where T: Ord {    
        type Item = &'a T;   
        
        fn next<'b>(&'b mut self) -> Option<Self::Item> {                        
            let mut c = self.current;
            while let Some(n) = c {
                self.path.push(n);
                c = n.left.root.as_ref();
            }
            self.path.pop().map(|n|{
                self.current = n.right.root.as_ref();
                &n.key
            })                             
        }
    }
}

No comments:

Post a Comment