File tree 2 files changed +51
-0
lines changed
main/java/by/andd3dfx/tree
test/java/by/andd3dfx/tree
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ package by .andd3dfx .tree ;
2
+
3
+ import lombok .AllArgsConstructor ;
4
+
5
+ /**
6
+ * Determine height/depth of binary tree
7
+ */
8
+ public class TreeHeight {
9
+
10
+ public static int calcHeight (Node node ) {
11
+ if (node == null ) {
12
+ return 0 ;
13
+ }
14
+
15
+ var leftHeight = calcHeight (node .left );
16
+ var rightHeight = calcHeight (node .right );
17
+ return 1 + Math .max (leftHeight , rightHeight );
18
+ }
19
+
20
+ @ AllArgsConstructor
21
+ public static class Node {
22
+ int value ;
23
+ Node left ;
24
+ Node right ;
25
+
26
+ public Node (int value ) {
27
+ this .value = value ;
28
+ }
29
+ }
30
+ }
Original file line number Diff line number Diff line change
1
+ package by .andd3dfx .tree ;
2
+
3
+ import by .andd3dfx .tree .TreeHeight .Node ;
4
+ import org .junit .Test ;
5
+
6
+ import static by .andd3dfx .tree .TreeHeight .calcHeight ;
7
+ import static org .assertj .core .api .Assertions .assertThat ;
8
+
9
+ public class TreeHeightTest {
10
+
11
+ @ Test
12
+ public void testCalcHeight () {
13
+ var two = new Node (2 );
14
+ var three = new Node (3 , new Node (4 ), null );
15
+ Node root = new Node (1 , two , three );
16
+
17
+ assertThat (calcHeight (root )).isEqualTo (3 );
18
+ assertThat (calcHeight (two )).isEqualTo (1 );
19
+ assertThat (calcHeight (three )).isEqualTo (2 );
20
+ }
21
+ }
You can’t perform that action at this time.
0 commit comments