AVL tree rotation in Java

前端 未结 3 692
Happy的楠姐
Happy的楠姐 2021-02-06 18:00

I want to implement the Java AVL tree and to rotate the tree left and right. I am not getting this.

Can anybody by looking at the code below tell me how can I possibly r

3条回答
  •  醉梦人生
    2021-02-06 18:27

    Full AVL tree implementation:

    public class AVLTree {
    
        private AVLNode root;
    
        private static class AVLNode {
    
            private T t;
            private int height;
            private AVLNode left;
            private AVLNode right;
    
            private AVLNode(T t) {
                this.t = t;
                height = 1;
            }
        }
    
        public void insert(T value) {
            root = insert(root, value);
        }
    
        private AVLNode insert(AVLNode n, T v) {
            if (n == null) {
                n = new AVLNode(v);
                return n;
            } else {
                int k = ((Comparable) n.t).compareTo(v);
                if (k > 0) {
                    n.left = insert(n.left, v);
                } else {
                    n.right = insert(n.right, v);
                }
                n.height = Math.max(height(n.left), height(n.right)) + 1;
                int heightDiff = heightDiff(n);
                if (heightDiff < -1) {
                    if (heightDiff(n.right) > 0) {
                        n.right = rightRotate(n.right);
                        return leftRotate(n);
                    } else {
                        return leftRotate(n);
                    }
                } else if (heightDiff > 1) {
                    if (heightDiff(n.left) < 0) {
                        n.left = leftRotate(n.left);
                        return rightRotate(n);
                    } else {
                        return rightRotate(n);
                    }
                } else;
    
            }
            return n;
        }
    
        private AVLNode leftRotate(AVLNode n) {
            AVLNode r = n.right;
            n.right = r.left;
            r.left = n;
            n.height = Math.max(height(n.left), height(n.right)) + 1;
            r.height = Math.max(height(r.left), height(r.right)) + 1;
            return r;
        }
    
        private AVLNode rightRotate(AVLNode n) {
            AVLNode r = n.left;
            n.left = r.right;
            r.right = n;
            n.height = Math.max(height(n.left), height(n.right)) + 1;
            r.height = Math.max(height(r.left), height(r.right)) + 1;
            return r;
        }
    
        private int heightDiff(AVLNode a) {
            if (a == null) {
                return 0;
            }
            return height(a.left) - height(a.right);
        }
    
        private int height(AVLNode a) {
            if (a == null) {
                return 0;
            }
            return a.height;
        }
    
    
    }
    

提交回复
热议问题