1448. Count Good Nodes in Binary Tree LeetCode Solution

In this guide, you will get 1448. Count Good Nodes in Binary Tree LeetCode Solution with the best time and space complexity. The solution to Count Good Nodes in Binary Tree problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Count Good Nodes in Binary Tree solution in C++
  4. Count Good Nodes in Binary Tree solution in Java
  5. Count Good Nodes in Binary Tree solution in Python
  6. Additional Resources
1448. Count Good Nodes in Binary Tree LeetCode Solution image

Problem Statement of Count Good Nodes in Binary Tree

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.

Example 1:

Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:

Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because “3” is higher than it.
Example 3:

Input: root = [1]
Output: 1
Explanation: Root is considered as good.

Constraints:

The number of nodes in the binary tree is in the range [1, 10^5].
Each node’s value is between [-10^4, 10^4].

See also  2249. Count Lattice Points Inside a Circle LeetCode Solution

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(h)

1448. Count Good Nodes in Binary Tree LeetCode Solution in C++

class Solution {
 public:
  int goodNodes(TreeNode* root, int mx = INT_MIN) {
    if (root == nullptr)
      return 0;
    const int newMax = max(mx, root->val);
    return (root->val >= mx) +              //
           goodNodes(root->left, newMax) +  //
           goodNodes(root->right, newMax);
  }
};
/* code provided by PROGIEZ */

1448. Count Good Nodes in Binary Tree LeetCode Solution in Java

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

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

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

1448. Count Good Nodes in Binary Tree LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.