Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Definition of a binary tree node
- class TreeNode {
- int val;
- TreeNode left;
- TreeNode right;
- TreeNode(int val) {
- this.val = val;
- left = null;
- right = null;
- }
- }
- // Class to find the node with the maximum value in a binary tree
- class BinaryTreeMaxNode {
- // Recursive function to find the node with the maximum value
- private TreeNode findMaxNode(TreeNode root, TreeNode maxNode) {
- if (root == null) {
- return maxNode;
- }
- if (root.val > maxNode.val) {
- maxNode = root;
- }
- TreeNode leftMax = findMaxNode(root.left, maxNode);
- TreeNode rightMax = findMaxNode(root.right, maxNode);
- if (leftMax.val > maxNode.val) {
- maxNode = leftMax;
- }
- if (rightMax.val > maxNode.val) {
- maxNode = rightMax;
- }
- return maxNode;
- }
- public TreeNode findMax(TreeNode root) {
- if (root == null) {
- return null;
- }
- return findMaxNode(root, root);
- }
- }
- // Example usage
- public class Main {
- public static void main(String[] args) {
- // Create a binary tree
- TreeNode root = new TreeNode(1);
- root.left = new TreeNode(5);
- root.right = new TreeNode(3);
- root.left.left = new TreeNode(9);
- root.left.right = new TreeNode(2);
- // Find the node with the maximum value
- BinaryTreeMaxNode binaryTreeMaxNode = new BinaryTreeMaxNode();
- TreeNode maxNode = binaryTreeMaxNode.findMax(root);
- System.out.println("Node with the maximum value: " + maxNode.val);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement