1448. Count Good Nodes in Binary Tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int goodNodes(TreeNode root) {
return dfs(root, Integer.MIN_VALUE);
}

private int dfs(TreeNode root, int maxValue) {
if (root == null) {
return 0;
}

int goodNodes = root.val >= maxValue ? 1 : 0;
maxValue = Math.max(root.val, maxValue);
return goodNodes + dfs(root.left, maxValue) + dfs(root.right, maxValue);
}
}

References

1448. Count Good Nodes in Binary Tree