본문 바로가기
Programming/LeetCode

[LeetCode] Trim a Binary Search Tree (트리 순환 재귀)

by 데이터현 2022. 4. 15.

https://leetcode.com/problems/trim-a-binary-search-tree/

 

Trim a Binary Search Tree - 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

재귀로 트리를 선회하는 방식이 이제 이해가 되는 거 같다.

 

# 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 trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
        if root is None:
            return None
        root.left = self.trimBST(root.left, low, high)
        root.right = self.trimBST(root.right, low, high)
        if low <= root.val <= high:
            return root
        else:
            if root.right:
                return root.right
            if root.left:
                return root.left
            return None

댓글