Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to find the deepest leaf node in a given binary tree
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- static int max_level = -1;
- static int deepest_leaf = -9999;
- static int deepest_level_leaf_node(node root){
- max_level = -1;
- deepest_leaf = -9999;
- deepest_level_leaf_node_helper(root, -1);
- return deepest_leaf;
- }
- // function to print the deepest leaf node in the binary tree using inorder traversal method
- static void deepest_level_leaf_node_helper(node root, int level){
- // if the tree is empty or if we reach a leaf node then return 0
- if (root == null){
- return;
- }
- // check in the left subtree for the element
- // if found then return the level
- deepest_level_leaf_node_helper(root.left, level + 1);
- if(root.left == null && root.right == null && max_level < level){
- max_level = max(max_level, level);
- deepest_leaf = root.data;
- }
- deepest_level_leaf_node_helper(root.right, level + 1);
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.println("Deepest Level leaf node in the above binary tree is : " + deepest_level_leaf_node(head));
- }
- }
Add Comment
Please, Sign In to add comment