938. Range Sum of BST

2021. 8. 3. 09:36·Algorithm
 

Range Sum of BST - 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

이진 탐색 트리의 low, high 값을 주면 low 이상 high 이하의 모든 노드의 값을 더해서 반환하는 문제다.

 

1. DFS, 완전 탐색

class Solution:
    answer = 0

    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        def dfs(cur):
            if low <= cur.val <= high:
                self.answer += cur.val

            if not cur.left and not cur.right:
                return

            if cur.left:
                dfs(cur.left)

            if cur.right:
                dfs(cur.right)

        dfs(root)
        return self.answer

이진 탐색 트리를 전부 탐색하면서 조건에 해당하는 값을 더한 뒤 반환한다.

이진 탐색 트리의 특징을 사용하지 않았다.

 

2. DFS, 이진 탐색 트리의 특징을 사용한 탐색

class Solution:
    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        def dfs(cur):
            if not cur:
                return 0
            answer = 0
            if low < cur.val:
                answer += dfs(cur.left)

            if cur.val < high:
                answer += dfs(cur.right)

            if low <= cur.val <= high:
                answer += cur.val

            return answer

        return dfs(root)

1번 방법과 비슷하지만 조건에 해당하는 범위만을 탐색하고 있다.

 

low는 이진 탐색 트리의 왼쪽 서브 트리에 해당하는 방향인데, 현재 노드의 값이 low보다 작다는 것은 적어도 현재 노드의 왼쪽 서브 트리는 탐색하지 않아도 된다는 뜻이다.

high는 이진 탐색 트리의 오른쪽 서브 트리에 해당하는 방향인데, 현재 노드의 값이 high보다 크다는 것은 적어도 현재 노드의 오른쪽 서브 트리는 탐색하지 않아도 된다는 뜻이다.

 

필요한 부분만을 탐색했기 때문에 소요시간도 줄었다.

 

3. Stack

class Solution:
    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        answer = 0
        stack = [root]
        while stack:
            cur = stack.pop()
            if cur:
                if low < cur.val:
                    stack.append(cur.left)
                if cur.val < high:
                    stack.append(cur.right)
                if low <= cur.val <= high:
                    answer += cur.val
        return answer

2번 풀이와 동일한 방법을 stack으로 구현했다.

'Algorithm' 카테고리의 다른 글

1315. Sum of Nodes with Even-Valued Grandparent  (0) 2021.08.05
1832. Check if the Sentence Is Pangram  (1) 2021.08.04
814. Binary Tree Pruning  (0) 2021.08.01
1038. Binary Search Tree to Greater Sum Tree  (0) 2021.07.31
807. Max Increase to Keep City Skyline  (0) 2021.07.30
'Algorithm' 카테고리의 다른 글
  • 1315. Sum of Nodes with Even-Valued Grandparent
  • 1832. Check if the Sentence Is Pangram
  • 814. Binary Tree Pruning
  • 1038. Binary Search Tree to Greater Sum Tree
Doljae
Doljae
  • Doljae
    Zero to Hero
    Doljae
  • 전체
    오늘
    어제
    • 분류 전체보기 (349)
      • Programming (54)
      • Algorithm (161)
      • Review (102)
      • Career (8)
      • Diary (18)
      • Shorts (4)
      • Temp (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글 쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    2021
    jpa
    공채
    회고
    한빛미디어
    인프콘
    db
    2023
    database
    2022
    java
    코딩
    sql
    코딩테스트
    프로그래머스
    라인
    백준
    AI
    나는 리뷰어다
    BOJ
    mysql
    ChatGPT
    컨퍼런스
    sql튜닝
    면접
    line
    PYTHON
    개발자
    나는리뷰어다
    leetcode
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Doljae
938. Range Sum of BST
상단으로

티스토리툴바