LeetCode 1448: Count Good Nodes in Binary Tree Solution

Master LeetCode problem 1448 (Count Good Nodes in Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1448. Count Good Nodes in Binary Tree

Problem Explanation

Explanation

To solve this problem, we can perform a depth-first search (DFS) traversal of the binary tree while keeping track of the maximum value encountered in the path from the root to the current node. If the current node's value is greater than or equal to the maximum value in the path, we increment the count of good nodes. We then recursively explore the left and right subtrees with the updated maximum value.

  • Start the DFS traversal from the root node with an initial maximum value of Integer.MIN_VALUE.
  • Keep track of the count of good nodes encountered during traversal.
  • At each node, update the maximum value in the path if necessary and check if the current node is a good node.
  • Recursively explore the left and right subtrees with the updated maximum value.
  • Return the count of good nodes at the end of traversal.

Time Complexity: O(N) where N is the number of nodes in the binary tree. Space Complexity: O(H) where H is the height of the binary tree (recursive stack space).

Solution Code

class Solution {
    public int goodNodes(TreeNode root) {
        return dfs(root, Integer.MIN_VALUE);
    }
    
    private int dfs(TreeNode node, int maxSoFar) {
        if (node == null) {
            return 0;
        }
        
        int count = 0;
        if (node.val >= maxSoFar) {
            count++;
            maxSoFar = node.val;
        }
        
        count += dfs(node.left, maxSoFar);
        count += dfs(node.right, maxSoFar);
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1448 (Count Good Nodes in Binary Tree)?

This page provides optimized solutions for LeetCode problem 1448 (Count Good Nodes in Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1448 (Count Good Nodes in Binary Tree)?

The time complexity for LeetCode 1448 (Count Good Nodes in Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1448 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1448 in Java, C++, or Python.

Back to LeetCode Solutions