diff --git a/src/main/java/cracking/the/code/interview/chapter4/BinaryTree.java b/src/main/java/cracking/the/code/interview/chapter4/BinaryTree.java index e1375a3..056b1b7 100644 --- a/src/main/java/cracking/the/code/interview/chapter4/BinaryTree.java +++ b/src/main/java/cracking/the/code/interview/chapter4/BinaryTree.java @@ -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); diff --git a/src/test/java/cracking/the/code/interview/chapter4/BinaryTreeTest.java b/src/test/java/cracking/the/code/interview/chapter4/BinaryTreeTest.java index 6014640..8771c7a 100644 --- a/src/test/java/cracking/the/code/interview/chapter4/BinaryTreeTest.java +++ b/src/test/java/cracking/the/code/interview/chapter4/BinaryTreeTest.java @@ -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."); } }