Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print the diameter of a given binary trees
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.util.*;
- // 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 {
- // function to find the height of a binary tree
- static int height(node root){
- if (root == null){
- return 0;
- }
- return (1 + max(height(root.left), height(root.right)));
- }
- // function to print the diameter of a binary tree
- static int diameter(node root){
- if (root == null){
- return 0;
- }
- int left_height = height(root.left);
- int right_height = height(root.right);
- int left_diameter = diameter(root.left);
- int right_diameter = diameter(root.right);
- return max( left_height + right_height + 1 , max(left_diameter, right_diameter) );
- }
- 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.print("Diameter of the Above binary tree is : " + diameter(head));
- }
- }
Add Comment
Please, Sign In to add comment