LeetCode 2445: Number of Nodes With Value One Solution

Master LeetCode problem 2445 (Number of Nodes With Value One), 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.

2445. Number of Nodes With Value One

Problem Explanation

Explanation

To solve this problem, we will traverse the given binary tree in a post-order manner. At each node, we will calculate the number of nodes with value 1 in the left and right subtrees. Then, we will update the count of nodes with value 1 in the current subtree and return this count to the parent node.

We will define a recursive function that takes a node as input and returns the count of nodes with value 1 in the subtree rooted at that node.

Solution Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {
    public int countNodesWithOne(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] count = new int[1];
        countNodes(root, count);
        return count[0];
    }

    private int countNodes(TreeNode node, int[] count) {
        if (node == null) {
            return 0;
        }
        int leftCount = countNodes(node.left, count);
        int rightCount = countNodes(node.right, count);
        
        if (node.val == 1) {
            count[0]++;
        }

        return leftCount + rightCount + (node.val == 1 ? 1 : 0);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2445 (Number of Nodes With Value One)?

This page provides optimized solutions for LeetCode problem 2445 (Number of Nodes With Value One) 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 2445 (Number of Nodes With Value One)?

The time complexity for LeetCode 2445 (Number of Nodes With Value One) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2445 on DevExCode?

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

Back to LeetCode Solutions