Add new node method in BST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
public class BinarySearchTree { | |
// BST Root Node | |
private Node root; | |
// Add new node to the BST | |
public void add(int val){ | |
this.root = add(root, val); | |
} | |
// Add new node to the BST recursive helper method | |
private Node add(Node root, int val){ | |
// null check | |
if(root == null) return new Node(val); | |
if(val < root.data){ | |
// add left child | |
root.left = add(root.left, val); | |
}else if(val > root.data){ | |
// add right child | |
root.right = add(root.right, val); | |
} | |
return root; | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment