#1448
Count Good Nodes in Binary Tree
medium· Treesruns: 0Given the root of a binary tree, a node X is named good if no node on the path from the root to X has a value greater than X's value. Return the number of good nodes in the binary tree.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 442
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node: TreeNode | None, max_so_far: int) -> int:
if not node:
return 0
count = 1 if node.val >= max_so_far else 0
max_so_far = max(max_so_far, node.val)
count += dfs(node.left, max_so_far)
count += dfs(node.right, max_so_far)
return count
return dfs(root, root.val)
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.