1623. Only Children

Easy1.5 points estimatedBinary TreeBreadth-First Search

In a seating chart drawn as a binary tree, a guest is alone when their parent has exactly one child, that is, they have no sibling. The root has no parent and is never alone.

Given the root of the tree, return an array with the values of all alone guests in level order: top level first and, within a level, from left to right. If nobody is alone, return an empty array.

A node whose parent has two children is skipped even if it has no children of its own, and a node with a single child makes that child count. Use a breadth-first traversal that checks each node's children as it is dequeued. Target complexity: O(n) time, O(n) space.

Example 1

Input:
root = [1,2,3,null,4,5,null]
Output:
[4,5]
Explanation:

Node 4 (child of 2) and node 5 (child of 3) have no sibling, so they are listed in level order as 4, 5.

Example 2

Input:
root = [7,3,8,1,4,6,9]
Output:
[]
Explanation:

Every internal node has two children, so no node is an only child.

Example 3

Input:
root = [10]
Output:
[]
Explanation:

The root never counts, so a single node gives an empty list.

Constraints

1 ≤ nodes ≤ 1000

-1000 ≤ Node.val ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…