Count Good Nodes in Binary Tree LeetCode solution in Java

1
class Solution {
2
int ans = 0;
3

4
public int goodNodes(TreeNode root) {
5
if (root == null) return 0;
6
dfs(root, root.val);
7
return ans;
8
}
9

10
void dfs(TreeNode root, int mx) {
11
if (root == null) return;
12

13
mx = Math.max(mx, root.val);
14
if (mx <= root.val) ans++;
15

16
dfs(root.left, mx);
17
dfs(root.right, mx);
18
}
19
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0