Find All The Lonely Nodes — LeetCode 1469 Python Solution

EasyLeetCode PremiumTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#1469
Reading time
4 min

The 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.

Example

Input
root = [1,2,3,null,4]
Output
[4]
Explanation
Light blue node is the only lonely node.

Python solution

Python
from typing import List, Optional

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def getLonelyNodes(root: Optional[TreeNode]) -> List[int]:
    res = []
    if not root:
        return res
    stack = [root]
    while stack:
        node = stack.pop()
        if node.left and not node.right:
            res.append(node.left.val)
        if node.right and not node.left:
            res.append(node.right.val)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return res

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1469. Find All The Lonely Nodes is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1469. Find All The Lonely Nodes?
LeetCode 1469. Find All The Lonely Nodes is rated Easy on LeetCode.
What is the time complexity of LeetCode 1469. Find All The Lonely Nodes?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1469. Find All The Lonely Nodes?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1469. Find All The Lonely Nodes cover?
LeetCode 1469. Find All The Lonely Nodes is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.
Is LeetCode 1469. Find All The Lonely Nodes a premium problem?
Yes. LeetCode 1469. Find All The Lonely Nodes is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview