From a282ec40a7dba4d13ee7b2e285edd44963ef60f3 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 16 May 2024 17:37:28 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2331.=20Evaluate=20Boolean?= =?UTF-8?q?=20Binary=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/evaluate-boolean-binary-tree.java | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 java/evaluate-boolean-binary-tree.java diff --git a/java/evaluate-boolean-binary-tree.java b/java/evaluate-boolean-binary-tree.java new file mode 100644 index 0000000..9600acc --- /dev/null +++ b/java/evaluate-boolean-binary-tree.java @@ -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⟩"); + }; + } +}