소프트웨어에 대한 모든 것

LeetCode 풀기 - 1325. Delete Leaves With a Given Value 본문

알고리즘/LeetCode

LeetCode 풀기 - 1325. Delete Leaves With a Given Value

앤테바 2021. 12. 20. 20:59
반응형

1325. Delete Leaves With a Given Value

https://leetcode.com/problems/delete-leaves-with-a-given-value/

 

Delete Leaves With a Given Value - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) Simple 재귀

이진 트리의 순회, 후위 순회에 대해서 이해하고 있다면 쉽게 풀 수 있는 문제입니다.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def removeLeafNodes(self, root, target):
        """
        :type root: TreeNode
        :type target: int
        :rtype: TreeNode
        """
        
        def recur(node):
            if node is None:
                return node
            node.left = recur(node.left)
            node.right = recur(node.right)
            if not node.left and not node.right and node.val == target:
                return None
            return node
        
        root = recur(root)
        return root

솔루션2)

솔루션1 좀 더 축약 버전의 코드입니다. recur() 함수를 제거하였습니다.

# 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 removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
        if not root:
            return None        
        root.left = self.removeLeafNodes(root.left, target)
        root.right = self.removeLeafNodes(root.right, target)
        if not root.left and not root.right and root.val == target:
            return None        
        return root
반응형
Comments