java: add «2331. Evaluate Boolean Binary Tree»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
4330c10e84
commit
a282ec40a7
1 changed files with 33 additions and 0 deletions
33
java/evaluate-boolean-binary-tree.java
Normal file
33
java/evaluate-boolean-binary-tree.java
Normal file
|
@ -0,0 +1,33 @@
|
|||
public class TreeNode {
|
||||
int val;
|
||||
TreeNode left;
|
||||
TreeNode right;
|
||||
|
||||
TreeNode() {}
|
||||
|
||||
TreeNode(int val) {
|
||||
this.val = val;
|
||||
}
|
||||
|
||||
TreeNode(int val, TreeNode left, TreeNode right) {
|
||||
this.val = val;
|
||||
this.left = left;
|
||||
this.right = right;
|
||||
}
|
||||
}
|
||||
|
||||
class Solution {
|
||||
public boolean evaluateTree(TreeNode node) {
|
||||
if (node == null) {
|
||||
throw new NullPointerException("node cannot be null");
|
||||
}
|
||||
|
||||
return switch (node.val) {
|
||||
case 0 -> false;
|
||||
case 1 -> true;
|
||||
case 2 -> evaluateTree(node.left) || evaluateTree(node.right);
|
||||
case 3 -> evaluateTree(node.left) && evaluateTree(node.right);
|
||||
default -> throw new IllegalStateException("value must be in range ⟨0;3⟩");
|
||||
};
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue