gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
find min and max in this binary code class Node1 { int value; Node1 left; Node1 right;…
- User
find min and max in this binary code class Node1 { int value; Node1 left; Node1 right;
public Node1(int value) { this.value = value; this.left = null; this.right = null; }}
public class BinarySearchTree {
public Node1 insert(int value, Node1 current) { if(current==null) { Node1 node = new Node1(value); return node; }else { if(value<current.value) { current.left=insert(value,current.left); }else { current.right=insert(value,current.right); } return current; } } public static void preorder(Node1 current){ if(current == null) { return; }else { System.out.println(current.value+" "); preorder(current.left); preorder(current.right); } } public static void main(String[] args) { BinarySearchTree var = new BinarySearchTree(); Node1 root = null; root = var.insert(50, root); root = var.insert(30, root); root = var.insert(20, root); root = var.insert(40, root); root = var.insert(70, root); root = var.insert(60, root); root = var.insert(80, root); var.preorder(root); }}
- Assistant
The minimum value in the binary search tree is 20 and the maximum value is 80.
- User
Write code for finding min and max in following binary code
- Assistant
To find the minimum and maximum values in the binary search tree, you can use the following methods in the BinarySearchTree class:
public class BinarySearchTree { ... public Node1 findMin(Node1 current) { if (current == null) return null; while (current.left != null) { current = current.left; } return current; } public Node1 findMax(Node1 current) { if (current == null) return null; while (current.right != null) { current = current.right; } return current; } ... }Then, in the main method, we can call these methods to find the min and max values:
public static void main(String[] args) { BinarySearchTree var = new BinarySearchTree(); Node1 root = null; root = var.insert(50, root); root = var.insert(30, root); root = var.insert(20, root); root = var.insert(40, root); root = var.insert(70, root); root = var.insert(60, root); root = var.insert(80, root); var.preorder(root); Node1 minNode = var.findMin(root); Node1 maxNode = var.findMax(root); System.out.println("Minimum value: " + minNode.value); System.out.println("Maximum value: " + maxNode.value); }This code will print the minimum and maximum values in the binary search tree.