1469. Find All The Lonely Nodes

Обновлено: 2024-03-12
1 мин
[]

Содержание

LeetCode problem 1469

# 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
class Solution:
    def getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]:
        def dfs(root):
            if root is None or (root.left is None and root.right is None):
                return
            if root.left is None:
                res.append(root.right.val)
            if root.right is None:
                res.append(root.left.val)
            dfs(root.left)
            dfs(root.right)

        res = []
        dfs(root)
        return res