forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
87 lines (70 loc) · 2.1 KB
/
Solution.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
/**
* @author Oleg Cherednik
* @since 24.09.2022
*/
public class Solution {
public static void main(String... args) {
Node root = createTree();
System.out.println(getTotalNodes(root)); // 10
}
private static int getTotalNodes(Node root) {
Data data = new Data();
dfs(root, 1, data);
return (int)Math.pow(2, data.height - 1) - 1 + data.lastLevelSize;
}
private static boolean dfs(Node parent, int curHeight, Data data) {
if (parent == null)
return true;
if (!data.heightFound)
data.height = Math.max(data.height, curHeight);
if (parent.left == null || parent.right == null) {
data.heightFound = true;
data.lastLevelSize++;
return parent.left == null;
}
return dfs(parent.left, curHeight + 1, data) && dfs(parent.right, curHeight + 1, data);
}
private static Node createTree() {
Node one = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
Node six = new Node(6);
Node seven = new Node(7);
Node eight = new Node(8);
Node nine = new Node(9);
Node ten = new Node(10);
one.left = two;
one.right = three;
two.left = four;
two.right = five;
three.left = six;
three.right = seven;
four.left = eight;
four.right = nine;
five.left = ten;
return one;
}
private static final class Node {
private final int val;
private Node left;
private Node right;
public Node(int val) {
this.val = val;
}
@Override
public String toString() {
return String.valueOf(val);
}
}
private static class Data {
private int height;
private boolean heightFound;
private int lastLevelSize;
@Override
public String toString() {
return String.valueOf(height + "-" + heightFound + '-' + lastLevelSize);
}
}
}