Friday 3 April 2015

JOSH :Diameter of a Binary Tree


Question: WAP that find out longest Diameter of Tree. The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree.
Solution
1. longest diameter with root
2.  longest diameter without root
package josh;

public class DiameterOFTree {
 public static int max(int x, int y) {// simple.
  if (x > y)
   return x;
  else
   return y;
 }

 public static int height(Node root) {
  // compare left height with right one...again simple
  if (root == null)
   return 0;
  else
   // never forget one..count of itself
   return 1 + max(height(root.left), height(root.right));
 }

 public static int diameter(Node root) {// 2 cases:with root,withoutroot
  // withRoot:leftMaxHeight+rightMaxHeight+1(root)
  // withOutRoot:use withRoot concept in left, right

  if (root == null)
   return 0;
  int lh = height(root.left);
  int rh = height(root.right);
  int ld = diameter(root.left);
  int rd = diameter(root.right);

  return max(lh + rh + 1, max(ld, rd));

 }

 public static void main(String[] args) {
  Node node1 = new Node(1, null, null);
  Node node2 = new Node(2, null, null);
  Node node3 = new Node(3, null, node1);
  Node node4 = new Node(4, node2, null);
  Node node5 = new Node(5, null, node3);
  Node node6 = new Node(6, node4, null);
  Node node7 = new Node(7, node6, node5);//Skew Tree

  System.out.println(diameter(node7));// included root
  node5 = new Node(5, node6, node3);
  node7 = new Node(7, null, node5);
  System.out.println(diameter(node7));// not included root

 }

 static class Node {
  int data;
  Node left;
  Node right;

  public Node(int data, Node left, Node right) {
   super();
   this.data = data;
   this.left = left;
   this.right = right;
  }
 }
}