-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2665471
commit e972c3c
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
17 changes: 17 additions & 0 deletions
17
src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
25
src/page-22/2331. Evaluate Boolean Binary Tree/evaluateTree.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}; |