A binary search tree is a binary tree where each node has a comparable key and satisfies the retriction that the key in any node is larger than the key in all nodes in that node's left sub-tree and smaller than the key in all nodes in that node's right sub-tree (wayne, 2021) import java.util.Scanner; class Node { int value; Node left; Node right; Node(int value) { this.value = value; this.left = null; this.right = null; } } class Tree { Node root; int height; int nElements; Tree() { this.root = null; this.height = - 1; this.nElements = 0; } void add(int value) { root = insertNode(root, value, 0); }
private Node insertNode(Node node, int value, int depth) { if (node == null) { Node newNode = new Node(value); newNode.left = null; newNode.right = null; nElements++; if (depth > height) { height = depth; } return newNode; } if (value < node.value) { node.left = insertNode(node.left, value, depth + 1); } else if (value > node.value) { node.right = insertNode(node.right, value, depth + 1); } return node; } void search(int value) { searchNode(root, value, 0); } private void searchNode(Node node, int value, int iteration) { if (node == null) { System.out.println("Node not found."); return; } if (value == node.value) { System.out.println("Node found on iteration: " + iteration); System.out.println("Node Depth: " + (height - iteration) + ", Tree Height: " + height);
return; } if (value < node.value) { searchNode(node.left, value, iteration + 1); } else if (value > node.value) { searchNode(node.right, value, iteration + 1); } } } public class Main { public static void main(String[] args) { Tree newTree = new Tree(); Scanner in = new Scanner(System.in); int newRecord; while (true) { System.out.print("Enter value to populate tree with (negative to exit): "); newRecord = in.nextInt(); if (newRecord < 0) break; newTree.add(newRecord); } int newSearch; while (true) { System.out.print("Enter value to search (negative to exit): "); newSearch = in.nextInt(); if (newSearch < 0) break; newTree.search(newSearch); } in.close(); }