forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.java
66 lines (55 loc) · 2.17 KB
/
BinaryTree.java
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
public class BinaryTree {
//Represent the node of binary tree
public static class Node{
int data;
Node left;
Node right;
public Node(int data){
//Assign data to the new node, set left and right children to null
this.data = data;
this.left = null;
this.right = null;
}
}
//Represent the root of binary tree
public Node root;
public BinaryTree(){
root = null;
}
//findHeight() will determine the maximum height of the binary tree
public int findHeight(Node temp){
//Check whether tree is empty
if(root == null) {
System.out.println("Tree is empty");
return 0;
}
else {
int leftHeight = 0, rightHeight = 0;
//Calculate the height of left subtree
if(temp.left != null)
leftHeight = findHeight(temp.left);
//Calculate the height of right subtree
if(temp.right != null)
rightHeight = findHeight(temp.right);
//Compare height of left subtree and right subtree
//and store maximum of two in variable max
int max = (leftHeight > rightHeight) ? leftHeight : rightHeight;
//Calculate the total height of tree by adding height of root
return (max + 1);
}
}
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
//Add nodes to the binary tree
bt.root = new Node(1);
bt.root.left = new Node(2);
bt.root.right = new Node(3);
bt.root.left.left = new Node(4);
bt.root.right.left = new Node(5);
bt.root.right.right = new Node(6);
bt.root.right.right.right= new Node(7);
bt.root.right.right.right.right = new Node(8);
//Display the maximum height of the given binary tree
System.out.println("Maximum height of given binary tree: " + bt.findHeight(bt.root));
}
}