Final answer:
To find the largest value in each level of a Binary Search Tree (BST) in Java, perform a level-order traversal using a queue, keeping track of the maximum value at each level and print it before proceeding to the next.
Step-by-step explanation:
Finding the Largest Value in Each Level of a Binary Search Tree
To find the largest value in each level of a binary search tree (BST) in Java, we need to perform a level-order traversal of the tree. This can be achieved using a queue data structure to traverse the tree in a breadth-first manner. During the traversal, we track the maximum value at each level and print it before moving to the next level. Here's a simple program that demonstrates this approach:
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
left = null;
right = null;
}
}
public class Main {
public static void findLargestValues(TreeNode root) {
if (root == null) {
return;
}
Queue queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
int levelMax = Integer.MIN_VALUE;
for (int i = 0; i < levelSize; i++) {
TreeNode currentNode = queue.poll();
if (currentNode.val > levelMax) {
levelMax = currentNode.val;
}
if (currentNode.left != null) {
queue.offer(currentNode.left);
}
if (currentNode.right != null) {
queue.offer(currentNode.right);
}
}
System.out.println("Largest value at current level: " + levelMax);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(7);
root.right.right = new TreeNode(18);
findLargestValues(root);
The class TreeNode represents a node in the BST. The findLargestValues function performs a level-order traversal and finds the largest value at each level. Note that in a BST, the largest value in each level is not necessarily the right-most node due to the tree's structure. This program will output the largest values for each level of the BST.