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
Find All The Lonely Nodes INPUT Binary Tree Structure 1 2 3 4 LONELY! root = [1,2,3,null,4] Has sibling Lonely node ALGORITHM (DFS) 1 Start DFS at root Visit node 1 (root) 2 Check children Node 1 has both L and R children (2 and 3) 3 Check node 2 Has only right child (4) Node 4 is lonely! 4 Check node 3 Has no children Nothing to add Lonely Check Logic: if only_left_child: add left to result if only_right_child: add right to result FINAL RESULT Lonely nodes identified: 1 2 3 4 Output: [4] Status: OK Node 4 has no sibling (only child of node 2) Key Insight: A node is lonely when its parent has exactly one child. During DFS traversal, check if a node has only a left child OR only a right child (but not both). If so, that single child is lonely. Time: O(n) | Space: O(h) where h is tree height TutorialsPoint - Find All The Lonely Nodes | DFS Approach
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