Problem

In a binary tree, a lonely node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node.

Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. Return the list in any order.

Examples

Example 1:

1
2
3
4
5
6
![](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1400-1499/1469.Find%20All%20The%20Lonely%20Nodes/images/e1.png)
Input: root = [1,2,3,null,4]
Output: [4]
Explanation: Light blue node is the only lonely node.
Node 1 is the root and is not lonely.
Nodes 2 and 3 have the same parent and are not lonely.

Example 2:

1
2
3
4
5
![](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1400-1499/1469.Find%20All%20The%20Lonely%20Nodes/images/e2.png)
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2]
Output: [6,2]
Explanation: Light blue nodes are lonely nodes.
Please remember that order doesn't matter, [2,6] is also an acceptable answer.

Example 3:

1
2
3
4
5
![](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1400-1499/1469.Find%20All%20The%20Lonely%20Nodes/images/tree.png)
Input: root = [11,99,88,77,null,null,66,55,null,null,44,33,null,null,22]
Output: [77,55,33,66,44,22]
Explanation: Nodes 99 and 88 share the same parent. Node 11 is the root.
All other nodes are lonely.

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • 1 <= Node.val <= 10^6

Solution

Method 1 – DFS Traversal

Intuition

Traverse the tree and whenever a node has only one child, add that child to the result.

Approach

  1. Use DFS (or BFS) to traverse the tree.
  2. At each node, if it has only one child, add that child’s value to the result.
  3. Continue recursively for both children.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import java.util.*;
class Solution {
    public List<Integer> getLonelyNodes(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }
    private void dfs(TreeNode node, List<Integer> res) {
        if (node == null) return;
        if (node.left != null && node.right == null) res.add(node.left.val);
        if (node.right != null && node.left == null) res.add(node.right.val);
        dfs(node.left, res);
        dfs(node.right, res);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def getLonelyNodes(root):
    res = []
    def dfs(node):
        if not node:
            return
        if node.left and not node.right:
            res.append(node.left.val)
        if node.right and not node.left:
            res.append(node.right.val)
        dfs(node.left)
        dfs(node.right)
    dfs(root)
    return res

Complexity

  • ⏰ Time complexity: O(N) where N = number of nodes.
  • 🧺 Space complexity: O(H) for recursion stack (H = tree height).