Skip to content

1448. Count Good Nodes in Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int goodNodes(TreeNode* root, int maxi = INT_MIN) {
    if (root == nullptr)
      return 0;

    const int newMax = max(maxi, root->val);
    return (root->val >= maxi) +            //
           goodNodes(root->left, newMax) +  //
           goodNodes(root->right, newMax);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int goodNodes(TreeNode root) {
    return goodNodes(root, Integer.MIN_VALUE);
  }

  private int goodNodes(TreeNode root, int max) {
    if (root == null)
      return 0;

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