Skip to content

Instantly share code, notes, and snippets.

@xnorcode
Last active October 3, 2018 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnorcode/74cf872569a9483d3c21c5b8d49a798b to your computer and use it in GitHub Desktop.
Save xnorcode/74cf872569a9483d3c21c5b8d49a798b to your computer and use it in GitHub Desktop.
Add new node method in BST
...
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