Advertisement
Coder_Group

Max node in Binary Tree Java

May 31st, 2023
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. // Definition of a binary tree node
  2. class TreeNode {
  3. int val;
  4. TreeNode left;
  5. TreeNode right;
  6.  
  7. TreeNode(int val) {
  8. this.val = val;
  9. left = null;
  10. right = null;
  11. }
  12. }
  13.  
  14. // Class to find the node with the maximum value in a binary tree
  15. class BinaryTreeMaxNode {
  16. // Recursive function to find the node with the maximum value
  17. private TreeNode findMaxNode(TreeNode root, TreeNode maxNode) {
  18. if (root == null) {
  19. return maxNode;
  20. }
  21.  
  22. if (root.val > maxNode.val) {
  23. maxNode = root;
  24. }
  25.  
  26. TreeNode leftMax = findMaxNode(root.left, maxNode);
  27. TreeNode rightMax = findMaxNode(root.right, maxNode);
  28.  
  29. if (leftMax.val > maxNode.val) {
  30. maxNode = leftMax;
  31. }
  32.  
  33. if (rightMax.val > maxNode.val) {
  34. maxNode = rightMax;
  35. }
  36.  
  37. return maxNode;
  38. }
  39.  
  40. public TreeNode findMax(TreeNode root) {
  41. if (root == null) {
  42. return null;
  43. }
  44.  
  45. return findMaxNode(root, root);
  46. }
  47. }
  48.  
  49. // Example usage
  50. public class Main {
  51. public static void main(String[] args) {
  52. // Create a binary tree
  53. TreeNode root = new TreeNode(1);
  54. root.left = new TreeNode(5);
  55. root.right = new TreeNode(3);
  56. root.left.left = new TreeNode(9);
  57. root.left.right = new TreeNode(2);
  58.  
  59. // Find the node with the maximum value
  60. BinaryTreeMaxNode binaryTreeMaxNode = new BinaryTreeMaxNode();
  61. TreeNode maxNode = binaryTreeMaxNode.findMax(root);
  62.  
  63. System.out.println("Node with the maximum value: " + maxNode.val);
  64. }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement