Hello! So I’m doing a 30 day coding challenge where I solve around 3-5 questions per day and thought of posting them here on my blog so that you guys can join the challenge too!
Welcome to Coding challenge Day 3: Problem 2! Be sure to post your answers, queries etc in the comments!!
Problem: Find maximum the element in a Binary tree
Solution:
- So this is the recursive method to solve this problem
- First we put the data in the root node in variable n (which stores the maximum element)
- Then we find the maximum element of the left subtree and right subtree
- Return the maximum value
package tree.binarytree;
// find max element in a binary tree
public class Program006 {
static class Node{
int data;
Node left_child, right_child;
public Node(int d){
data=d;
left_child=right_child=null;
}
}
static class Binary_tree {
Node root;
public Binary_tree(){
root=null;
}
public int find_max_element (Node node){
if(node==null)
return Integer.MIN_VALUE;
int n= node.data; //n is max element
int nl= find_max_element(node.left_child);
int nr= find_max_element(node.right_child);
if (nl>n)
n=nl;
else if (nr>n)
n=nr;
return n;
}
}
public static void main (String [] args){
Binary_tree tree= new Binary_tree();
tree.root = new Node(12);
tree.root.left_child = new Node(17);
tree.root.right_child = new Node(54);
tree.root.left_child.right_child = new Node(36);
tree.root.left_child.right_child.left_child = new Node(122);
tree.root.left_child.right_child.right_child = new Node(111);
tree.root.right_child.right_child = new Node(9);
tree.root.right_child.right_child.left_child = new Node(40);
System.out.println("Maximum element is " +
tree.find_max_element(tree.root));
}
}
Glossary:
1. Integer.MIN_VALUE
Happy Learning!!