LeetCode 2792: Count Nodes That Are Great Enough Solution

Master LeetCode problem 2792 (Count Nodes That Are Great Enough), a hard 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.

2792. Count Nodes That Are Great Enough

Problem Explanation

Explanation:

The problem asks to count the number of nodes in a binary tree that have at least one descendant whose value is greater than or equal to the node's value.

To solve this problem, we can perform a post-order traversal of the binary tree. At each node, we recursively calculate the number of "great enough" nodes in its left subtree and right subtree. Then we compare the maximum value in the left subtree and right subtree with the current node's value to determine if the current node is "great enough". If it is, we increment the count.

The time complexity of this solution is O(n) where n is the number of nodes in the binary tree. The space complexity is O(h) where h is the height of the binary tree.

:

Solution Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    public int countGreatEnoughNodes(TreeNode root) {
        int[] count = new int[1];
        helper(root, count);
        return count[0];
    }

    private int[] helper(TreeNode node, int[] count) {
        if (node == null) {
            return new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
        }

        int[] left = helper(node.left, count);
        int[] right = helper(node.right, count);

        int maxLeft = Math.max(left[0], left[1]);
        int maxRight = Math.max(right[0], right[1]);

        if (maxLeft >= node.val || maxRight >= node.val) {
            count[0]++;
        }

        return new int[]{Math.max(node.val, Math.max(maxLeft, maxRight)), Math.max(maxLeft, maxRight)};
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2792 (Count Nodes That Are Great Enough)?

This page provides optimized solutions for LeetCode problem 2792 (Count Nodes That Are Great Enough) 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 2792 (Count Nodes That Are Great Enough)?

The time complexity for LeetCode 2792 (Count Nodes That Are Great Enough) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2792 on DevExCode?

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

Back to LeetCode Solutions