Visible Tree Node - Depth First Search / DFS on Tree

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;

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.

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.