Problem statement

https://leetcode.com/problems/find-all-the-lonely-nodes/

Solution

Just perfrom classical dfs, chechking each time for lonely nodes.

Complexity

Time complexity is O(n), space complexity can be potentially O(n) as well.

Code

class Solution:
    def getLonelyNodes(self, root):
        self.ans = []
        def dfs(node):
            if node.right and not node.left:
                self.ans += [node.right.val]
            if node.left and not node.right:
                self.ans += [node.left.val]
            for child in filter(None, [node.left, node.right]):
                dfs(child)
                
        dfs(root)
        return self.ans