Folks,
Math.max(maxSoFar, root.val)
Seems redundant as we will any ways check root.val >= maxSoFar β just doing the following still works?
int totalCount = 0;
if (root!=null){
if (root.val >= maxSoFar){
totalCount++;
max = root.val;
}
totalCount += countVisibleNodes(root.left,maxSoFar);
totalCount += countVisibleNodes(root.right,maxSoFar);
}
return totalCount;
null68
42
Sorry but the wording of the problem is very misleading.
Could simply be: a node is visible if it is the maximum value in the path to the root.
Lenur
44
There is a solution with global variable:
private static int total = 0;
public static int dfs(Node<Integer> root, int maxSoFar) {
if (root == null) {
return 0;
}
if (root.val >= maxSoFar) {
maxSoFar = root.val;
total++;
}
dfs(root.left, maxSoFar);
dfs(root.right, maxSoFar);
return total;
}
are you sure itβs max value among the node visited, I doubt it is rather max value among the elements in the call stack.