Solved at: 2022-08-27
Given a binary tree
root, a node X in the tree is named good if in the path from the root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
def countGoodNodes(self, node: TreeNode, maxVal: int) -> int:
if not node:
count = 0
if not maxVal > node.val:
count += 1
if node.val > maxVal:
maxVal = node.val
count = count + self.countGoodNodes(node.left, maxVal) + self.countGoodNodes(node.right, maxVal)
def goodNodes(self, root: TreeNode) -> int:
return self.countGoodNodes(root, root.val)
436 ms, faster than 36.72% of Python3 online submissions for Count Good Nodes in Binary Tree.
32.6 MB, less than 45.65% of Python3 online submissions for Count Good Nodes in Binary Tree.