BackeasyTrees Swiggy

Count Single-Child Nodes Solution

Problem Statement

Given the root of a binary tree, return the total number of nodes that have exactly one child (either a left child or a right child, but not both).

Example 1
Input
root = [1, 2, 3, 4]
Output
1

Explanation: Node 2 has only one child (4). Node 1 has two children (2, 3). Nodes 3 and 4 have zero children. Thus, there is only 1 node with exactly one child.

Example 2
Input
root = [1, 2, null, 3]
Output
2

Explanation: Node 1 has only one child (2). Node 2 has only one child (3). Node 3 has zero children. Thus, there are 2 nodes with exactly one child.

Constraints

  • The number of nodes in the tree is in the range [0, 1000].
  • -100 <= Node.val <= 100
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free