Skip to content

Commit

Permalink
binary search tree
Browse files Browse the repository at this point in the history
  • Loading branch information
brendonmiranda committed Sep 14, 2024
1 parent 6a7f9c9 commit 045344b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/main/java/cracking/the/code/interview/chapter4/BinaryTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,30 @@ public Node insert(Node root, int v) {
return root;
}

if (v <= root.value)
if (v < root.value)
root.left = insert(root.left, v);
else
else if (v > root.value)
root.right = insert(root.right, v);

return root;
}

public Node search(Node root, int v) {

if (root == null) {
throw new RuntimeException(v + " Not found.");
}

if (v == root.value) {
return root;
}else if (v < root.value ) {
return search(root.left, v);
} else {
return search(root.right, v);
}

}

public void inOrderTraversal(Node n) {
if (n != null) {
inOrderTraversal(n.left);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ public void test() {
binaryTree.insert(root, 2);
binaryTree.insert(root, 1);
binaryTree.insert(root, 6);
binaryTree.insert(root, 6); //(it should not allow to repeat)
binaryTree.insert(root, 20);

binaryTree.inOrderTraversal(root);

var v = binaryTree.search(root, 8);
System.out.println(v.value + " Found.");
}

}

0 comments on commit 045344b

Please sign in to comment.