Find All The Lonely Nodes - Problem

Imagine exploring a family tree where some children are only children while others have siblings. In this binary tree problem, we need to identify all the lonely nodes - those that are the only child of their parent.

A lonely node is defined as a node that has no siblings (i.e., it's either the only left child or the only right child of its parent). The root node is never considered lonely since it has no parent.

Goal: Given the root of a binary tree, return an array containing the values of all lonely nodes. The order of the result doesn't matter.

Example: In a tree where node 5 has only a left child (node 3), then node 3 is lonely. Similarly, if node 7 has only a right child (node 9), then node 9 is lonely.

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [1,2,3,null,4]
โ€บ Output: [4]
๐Ÿ’ก Note: Node 2 has only one child (node 4), so node 4 is lonely. Node 3 has no children and node 1 has two children, so no other nodes are lonely.
example_2.py โ€” Multiple Lonely Nodes
$ Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2]
โ€บ Output: [6,2]
๐Ÿ’ก Note: Node 1 has only left child 6 (so 6 is lonely), and node 3 has only right child 2 (so 2 is lonely).
example_3.py โ€” No Lonely Nodes
$ Input: root = [1,2,3]
โ€บ Output: []
๐Ÿ’ก Note: Root has two children, and the leaf nodes have no children. No node is the only child of its parent.

Constraints

  • The number of nodes in the tree is in the range [1, 1000]
  • 1 โ‰ค Node.val โ‰ค 1000
  • Each node value is unique

Visualization

Tap to expand
Finding Lonely Nodes: The Family Detective๐Ÿ‘จโ€๐Ÿ’ผ 1๐Ÿ‘ฉ 2๐Ÿ‘จ 3๐Ÿง’ 4๐Ÿ‘ถ 5Detective's Findings:โ€ข Node 1: Has 2 children โŒโ€ข Node 2: Has 1 child โœ“โ€ข Node 3: Has 1 child โœ“Lonely Nodes: [4, 5]Algorithm Steps:1. Visit each parent node2. Count children: 0, 1, or 23. If count = 1, child is lonely4. Time: O(n), Space: O(h)
Understanding the Visualization
1
Start at the Top
Begin your walk from the family patriarch/matriarch at the root of the tree
2
Check Each Family Unit
At each parent, count their children: 0, 1, or 2 children
3
Spot Only Children
If a parent has exactly 1 child, that child is lonely (an only child)
4
Record and Continue
Add the lonely child to your list and continue visiting other family groups
5
Complete the Walk
After visiting all families once, you have found all only children
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking each node to find its parent (O(nยฒ)), we reverse the approach and check each parent to identify their only children (O(n)). This single-pass solution is both intuitive and optimal!
Asked in
Facebook 25 Amazon 18 Google 12 Microsoft 8
23.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen