-
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
60e0777
commit ec88181
Showing
3 changed files
with
60 additions
and
8 deletions.
There are no files selected for viewing
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
22 changes: 22 additions & 0 deletions
22
src/page-14/1448. Count Good Nodes in Binary Tree/goodNodes.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,22 @@ | ||
import { generateBinaryTree } from '~/utils/binary-tree'; | ||
|
||
import { goodNodes } from './goodNodes'; | ||
|
||
describe('1448. Count Good Nodes in Binary Tree', () => { | ||
test('goodNodes', () => { | ||
{ | ||
const root = generateBinaryTree([3, 1, 4, 3, null, 1, 5]); | ||
expect(goodNodes(root)).toBe(4); | ||
} | ||
|
||
{ | ||
const root = generateBinaryTree([3, 3, null, 4, 2]); | ||
expect(goodNodes(root)).toBe(3); | ||
} | ||
|
||
{ | ||
const root = generateBinaryTree([1]); | ||
expect(goodNodes(root)).toBe(1); | ||
} | ||
}); | ||
}); |
29 changes: 29 additions & 0 deletions
29
src/page-14/1448. Count Good Nodes in Binary Tree/goodNodes.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,29 @@ | ||
import type { TreeNode } from '~/utils/binary-tree'; | ||
|
||
type GoodNodes = (root: TreeNode | null) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const goodNodes: GoodNodes = (root) => { | ||
// Helper function to perform DFS | ||
function dfs(node: TreeNode | null, maxVal: number): number { | ||
if (node === null) return 0; | ||
|
||
// Determine if the current node is a "good" node | ||
let count = 0; | ||
if (node.val >= maxVal) count = 1; | ||
|
||
// Update maxVal for the next recursion | ||
const newMaxVal = Math.max(maxVal, node.val); | ||
|
||
// Continue DFS on left and right children | ||
count += dfs(node.left, newMaxVal); | ||
count += dfs(node.right, newMaxVal); | ||
|
||
return count; | ||
} | ||
|
||
// Start DFS with the root node | ||
return dfs(root, root?.val ?? Number.NEGATIVE_INFINITY); | ||
}; |