1448. Count Good Nodes in Binary Tree
Problem
A node is "good" if no node on the path from the root to it has a greater value. Count the good nodes of a binary tree.
Example: [3,1,4,3,null,1,5] → 4
Constraints: up to 10⁵ nodes.
Pass down the max value on the path from the root; a node is good if node.val ≥ pathMax.
Complexity: O(n).
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node, mx):
if not node:
return 0
good = node.val >= mx
mx = max(mx, node.val)
return good + dfs(node.left, mx) + dfs(node.right, mx)
return dfs(root, root.val)
assert Solution().goodNodes(make_tree([3, 1, 4, 3, None, 1, 5])) == 4
assert Solution().goodNodes(make_tree([3, 3, None, 4, 2])) == 3
class Solution {
public int goodNodes(TreeNode root) { return dfs(root, Integer.MIN_VALUE); }
private int dfs(TreeNode n, int mx) {
if (n == null) return 0;
int good = n.val >= mx ? 1 : 0;
mx = Math.max(mx, n.val);
return good + dfs(n.left, mx) + dfs(n.right, mx);
}
}
func goodNodes(root *TreeNode) int {
var dfs func(node *TreeNode, mx int) int
dfs = func(node *TreeNode, mx int) int {
if node == nil {
return 0
}
good := 0
if node.Val >= mx { // nothing bigger on the path from the root
good = 1
}
mx = max(mx, node.Val)
return good + dfs(node.Left, mx) + dfs(node.Right, mx)
}
return dfs(root, root.Val)
}