forked from KIET7UKE/Hacktoberfest-2K22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeightTree.java
105 lines (47 loc) · 1.25 KB
/
HeightTree.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import java.util.*;
public class widthHeight {
static Node root;
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
void add(int data) {
root = insert(root, data);
}
Node insert(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
}
if (data < root.data) {
root.left = insert(root.left, data);
} else if (data > root.data) {
root.right = insert(root.right, data);
}
return root;
}
public int treeHeight(Node root) {
if (root == null) {
return -1;
} else {
return 1 + Math.max(treeHeight(root.left), treeHeight(root.right));
}
}
public static void main(String[] args) {
widthHeight tree = new widthHeight();
tree.add(50);
tree.add(30);
tree.add(10);
tree.add(5);
tree.add(40);
tree.add(80);
tree.add(70);
tree.add(150);
int h = tree.treeHeight(root);
System.out.println("Height of tree is: " + h);
}
}