Problem Description
In a binary tree, a lonely node is defined as a node that is the only child of its parent. The root is not considered lonely because it does not have a parent. Given the root of the tree, return an array of all lonely node values in any order.
Key Insights
- Traverse the tree using either a DFS (recursive) or BFS (iterative) approach.
- At each node, check if it has exactly one child.
- If a node has only one non-null child, that child is lonely and should be added to the result list.
- Continue traversing until all nodes in the tree are processed.
Space and Time Complexity
Time Complexity: O(n), where n is the total number of nodes in the tree, since each node is visited once. Space Complexity: O(h), where h is the height of the tree. In the worst-case (skewed tree) this becomes O(n).
Solution
We perform a depth-first search (DFS) on the tree. For each node, we check if it has exactly one child. If so, we add that child’s value to our result list. The recursion continues for both children of the current node. The root is ignored because it has no parent. This approach ensures an efficient and straightforward solution.