Problem statement

https://binarysearch.com/problems/Only-Child/

Solution

Just use usual dfs/bfs and traverse tree.

Complexity

It is O(n) for time and O(h) for space.

Code

class Solution:
    def solve(self, root):
        self.ans = 0
        def dfs(node):
            if not node: return
            if node.left and not node.right: self.ans += 1
            if node.right and not node.left: self.ans += 1
            dfs(node.left)
            dfs(node.right)

        dfs(root)
        return self.ans