LeetCode 3054: Binary Tree Nodes Solution
Master LeetCode problem 3054 (Binary Tree Nodes), 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.
3054. Binary Tree Nodes
Problem Explanation
Explanation:
To solve this problem, we can perform a depth-first search (DFS) on the binary tree and count the number of nodes at each level. We will maintain a list to store the count of nodes at each level. Then, we can return this list as the result.
- Perform a DFS traversal starting from the root node.
- Keep track of the current level while traversing the tree.
- Increment the count of nodes at the current level in the list.
- Recur for the left and right child nodes with an increased level.
- Return the list of node counts.
Time Complexity:
The time complexity of this approach is O(N), where N is the number of nodes in the binary tree.
Space Complexity:
The space complexity of this approach is O(N) for the recursive stack space.
: :
Solution Code
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public List<Integer> countNodes(TreeNode root) {
List<Integer> nodeCounts = new ArrayList<>();
countNodesDFS(root, nodeCounts, 0);
return nodeCounts;
}
private void countNodesDFS(TreeNode node, List<Integer> nodeCounts, int level) {
if (node == null) return;
if (nodeCounts.size() <= level) {
nodeCounts.add(1);
} else {
nodeCounts.set(level, nodeCounts.get(level) + 1);
}
countNodesDFS(node.left, nodeCounts, level + 1);
countNodesDFS(node.right, nodeCounts, level + 1);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3054 (Binary Tree Nodes)?
This page provides optimized solutions for LeetCode problem 3054 (Binary Tree Nodes) 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 3054 (Binary Tree Nodes)?
The time complexity for LeetCode 3054 (Binary Tree Nodes) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3054 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3054 in Java, C++, or Python.