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; +};