Algo-Sim › Binary Trees & BST

Count Good Nodes in Binary Tree

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

A node is good if no value on the path from the root to it is larger. Carry the path maximum down a DFS.

Problem

Given the root of a binary tree, a node X is good if no node on the path from the root to X has a value greater than X. Return the number of good nodes. The root is always good.

Constraints

Edge cases to test

Follow-up questions

Why pass the maximum down?
Each node only needs the largest value above it, so one O(n) DFS with O(h) stack is enough.
Iterative version?
A stack of (node, max so far) pairs.

Solution

Java

public int goodNodes(TreeNode root) {
    return count(root, Integer.MIN_VALUE);
}

private int count(TreeNode node, int maxSoFar) {
    if (node == null) return 0;
    int good = node.val >= maxSoFar ? 1 : 0;
    int best = Math.max(maxSoFar, node.val);
    int left = count(node.left, best);
    int right = count(node.right, best);
    return good + left + right;
}

Python

def good_nodes(root):
    def count(node, max_so_far):
        if not node:
            return 0
        good = 1 if node.val >= max_so_far else 0
        best = max(max_so_far, node.val)
        left = count(node.left, best)
        right = count(node.right, best)
        return good + left + right

    return count(root, float("-inf"))

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int goodNodes(TreeNode *root) {
        return count(root, INT_MIN);
    }

    int count(TreeNode *node, int maxSoFar) {
        if (node == nullptr)
            return 0;
        int good = node->val >= maxSoFar ? 1 : 0;
        int best = std::max(maxSoFar, node->val);
        int left = count(node->left, best);
        int right = count(node->right, best);
        return good + left + right;
    }
};

More Binary Trees & BST problems