Skip to content

Commit

Permalink
167th Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Jul 15, 2024
1 parent 2665471 commit e972c3c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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);
}
});
});
25 changes: 25 additions & 0 deletions src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.ts
Original file line number Diff line number Diff line change
@@ -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;
};

0 comments on commit e972c3c

Please sign in to comment.