-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_04.java
More file actions
73 lines (58 loc) · 1.74 KB
/
Copy pathBT_Problem_04.java
File metadata and controls
73 lines (58 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package trees.binaryTree;
/* Problem Title :- Find the Diameter of a tree or Width of tree.
*
* Diameter of a tree :-
* The Diameter of a tree is the number of nodes on the longest path
* between two end nodes.
*/
class Node {
int data;
Node root, left, right;
public Node(int value) {
data = value;
root = left = right = null;
}
}
// Class to print the Diameter.
public class BT_Problem_04 {
Node root;
// Method to calculate the diameter and return it to main
int diameter(Node root) {
// base case if tree is empty
if (root == null)
return 0;
// get the height of left and right sub-trees
int leftheight = height(root.left);
int rightheight = height(root.right);
// get the diameter of left and right sub-trees
int leftdiameter = diameter(root.left);
int rightdiameter = diameter(root.right);
return Math.max(leftheight + rightheight + 1, Math.max(leftdiameter, rightdiameter));
}
// A wrapper over diameter(Node root)
int diameter() {
return diameter(root);
}
/*
* The function Compute the "height" of a tree.
* Height is the number of nodes along the longest path
* from the root node to the farthest leaf node.
*/
static int height(Node node) {
if (node == null)
return 0;
// If tree is not empty then height = 1 + max of left height and right heights.
return (1 + Math.max(height(node.left), height(node.left)));
}
// Driver Code
public static void main(String[] args) {
BT_Problem_04 tree = new BT_Problem_04();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
// Function Call
System.out.println("The diameter of given bianry tree is : " + tree.diameter());
}
}