Skip to content

Commit ada2283

Browse files
committed
Add TreeHeight task solution
1 parent 6816b22 commit ada2283

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Diff for: src/main/java/by/andd3dfx/tree/TreeHeight.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

Diff for: src/test/java/by/andd3dfx/tree/TreeHeightTest.java

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
}

0 commit comments

Comments
 (0)