From e972c3c9128e7f2c1ed2b1939c31c9439f2b44aa Mon Sep 17 00:00:00 2001 From: Shyam-Chen Date: Mon, 15 Jul 2024 14:26:13 +0800 Subject: [PATCH] 167th Commit --- .../evaluateTree.test.ts | 17 +++++++++++++ .../evaluateTree.ts | 25 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.test.ts create mode 100644 src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.ts diff --git a/src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.test.ts b/src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.test.ts new file mode 100644 index 0000000..47981e2 --- /dev/null +++ b/src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.test.ts @@ -0,0 +1,17 @@ +import { generateBinaryTree } from '~/utils/binary-tree'; + +import { evaluateTree } from './evaluateTree'; + +describe('2331. Evaluate Boolean Binary Tree', () => { + test('evaluateTree', () => { + { + const root = generateBinaryTree([2, 1, 3, null, null, 0, 1]); + expect(evaluateTree(root)).toBe(true); + } + + { + const root = generateBinaryTree([0]); + expect(evaluateTree(root)).toBe(false); + } + }); +}); diff --git a/src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.ts b/src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.ts new file mode 100644 index 0000000..0c72e43 --- /dev/null +++ b/src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.ts @@ -0,0 +1,25 @@ +import type { TreeNode } from '~/utils/binary-tree'; + +type EvaluateTree = (root: TreeNode | null) => boolean; + +/** + * Accepted + */ +export const evaluateTree: EvaluateTree = (root) => { + if (root === null) return false; + + // If the node is a leaf node, return its boolean value. + if (root.val === 0) return false; + if (root.val === 1) return true; + + // Recursively evaluate left and right children. + const leftEval = evaluateTree(root.left); + const rightEval = evaluateTree(root.right); + + // Apply the boolean operation based on the node's value. + if (root.val === 2) return leftEval || rightEval; // OR operation + if (root.val === 3) return leftEval && rightEval; // AND operation + + // Default return value (should not reach here in a properly formed tree). + return false; +};