eugenp / tutorials

Just Announced - "Learn Spring Security OAuth":
http://bit.ly/github-lsso
MIT License
36.62k stars 54.48k forks source link

Reformulate `node` to `root` for method `insert()` in AVL tree #14737

Closed alghe-global closed 11 months ago

alghe-global commented 1 year ago

From:

    private Node insert(Node node, int key) { 
         if (node == null) { 
             return new Node(key); 
         } else if (node.key > key) { 
             node.left = insert(node.left, key); 
         } else if (node.key < key) { 
             node.right = insert(node.right, key); 
         } else { 
             throw new RuntimeException("duplicate Key!"); 
         } 
         return rebalance(node); 
     }

To:

    private Node insert(Node root, int key) { 
         if (root == null) { 
             return new Node(key); 
         } else if (root.key > key) { 
             root.left = insert(root.left, key); 
         } else if (root.key < key) { 
            root.right = insert(root.right, key); 
         } else { 
             throw new RuntimeException("duplicate Key!"); 
         } 
         return rebalance(root); 
     }

This will make it clear that rebalancing has to happen at the root in order to maintain AVL property (all nodes should not differ by at most 1 [1, 0, -1]).

alghe-global commented 1 year ago

N.B. probably article https://www.baeldung.com/java-avl-trees#insert-node-avl should be updated as well to reflect this change.

ulisseslima commented 1 year ago

Hey, @alghe-global.

Thanks for the feedback. We'll look into this and update the article if necessary.

This issue will remain open until then.

kasramp commented 11 months ago

Hi @alghe-global - we renamed the variable for clarity sake and updated the article.