Finding the maximum node in a Binary Tree - Two methods ( Java )
Input
10 20 30 40 50 60 70
Output
70
Method 1 :
Using Queue and List
Traversing all the nodes of the tree using the queue and storing all the values of the node in the list and returning the maximum value in the List.
Code
import java.util.*; class Nod{ int data; Nod left,right; Nod(int k) { data=k; } } public class MaxNode { public static int getMax(Nod root) { if(root==null) return -1; Queue <Nod> q=new LinkedList<Nod>(); List<Integer> arr=new ArrayList<Integer>(); q.add(root); arr.add(root.data); while(q.isEmpty()==false) { Nod curr=q.poll(); arr.add(curr.data); if(curr.left!=null) q.add(curr.left); if(curr.right!=null) q.add(curr.right); } return Collections.max(arr); } public static void main(String[] args) { Nod root=new Nod(10); // 10 root.left=new Nod(20); // 20 30 root.right=new Nod(30); // 40 50 60 70 root.left.left=new Nod(40); root.left.right=new Nod(50); root.right.left=new Nod(60); root.right.right=new Nod(70); System.out.println(getMax(root)); } }
Method 2 ( Efficient )
Using simple recursion
Simply comparing the current root data with the maximum node values of the subtree (i.e left subtree and right subtree) using recursion.
Code
import java.util.*; class Nod{ int data; Nod left,right; Nod(int k) { data=k; } } public class MaxNode { //Efficient Method public static int getMax(Nod root) { if(root==null) return Integer.MIN_VALUE; return Math.max(root.data, Math.max(getMax(root.left), getMax(root.right))); } public static void main(String[] args) { Nod root=new Nod(10); // 10 root.left=new Nod(20); // 20 30 root.right=new Nod(30); // 40 50 60 70 root.left.left=new Nod(40); root.left.right=new Nod(50); root.right.left=new Nod(60); root.right.right=new Nod(70); System.out.println(getMax(root)); } }
Output :
Input 10 20 30 40 50 60 70 Output 70
If you have any doubts regarding the code, then feel free to comment down below. Our moderators will resolve your queries.
If you want to contribute articles and codes in Codinhumans official website the email us at codinghumanshelp@gmail.com. See the details regarding writing the contents here
Write for Codinghumans