[LeetCode#938] Range Sum of BST

2024. 9. 25. 19:13·Algorithm/문제풀이

❒ Description


날짜 2024.09.25 (수)
레벨 Easy
제목 Range Sum of BST
링크  https://leetcode.com/problems/range-sum-of-bst/description/
자료구조 BST

 

 

 

 

 

❒ 문제 분석


트리에서 부모노드 보다 작은 노드는 왼쪽으로, 큰 노드는 오른쪽에 위치한다. 이번 문제에서는 가장 작은 값 low와

가장 큰 값 high를 제시해준다. 따라서 재귀 구조로 트리를 순회할 때 현재 노드의 값이 low 보다 작다면 오른쪽만

탐색하고, 현재 노드의 값이 high 보다 크다면 왼쪽만 탐색한다. 

  • root < low : 오른쪽만 탐색
  • root > high : 왼쪽만 탐색

 

 

 

 

❒ Solution


1. 트리의 특징을 통한 문제해결

public int rangeSumBST(TreeNode root, int low, int high) {
    return accNode(root, low, high);
}

public int accNode(TreeNode root, int low, int high) {
    if (root == null) return 0;
    int acc = 0;
    int target = root.val;
    if (target >= low && target <= high) {
        acc += target;
    }
    if (target < low) {
        acc += accNode(root.right, low, high);
    }
    if (target > high) {
        acc += accNode(root.left, low, high);
    }
}

 

 

 

 

 


'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#105]Construct BT from Preorder and Inorder Traversal  (0) 2024.09.26
[LeetCode#783] Minimum Distance Between BST Nodes  (0) 2024.09.25
[LeetCode#1038] Binary Search Tree to Greater Sum Tree  (0) 2024.09.25
[LeetCode#108] Convert Sorted Array to Binary Search Tree  (0) 2024.09.25
[LeetCode#310] Minimum Height Trees  (0) 2024.09.24
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#105]Construct BT from Preorder and Inorder Traversal
  • [LeetCode#783] Minimum Distance Between BST Nodes
  • [LeetCode#1038] Binary Search Tree to Greater Sum Tree
  • [LeetCode#108] Convert Sorted Array to Binary Search Tree
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (207)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (6)
        • Java (3)
        • Kotlin (3)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (39)
        • 친절한 SQL 튜닝 (9)
        • 데이터 중심 애플리케이션 설계 (14)
        • 이벤트 기반 마이크로서비스 구축 (6)
        • Spring Batch docs (10)
        • Quartz docs (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    binarysearch
    sliding-window
    오블완
    Back-Tracking
    부분단조성
    greedy
    Two-Pointer
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#938] Range Sum of BST
상단으로

티스토리툴바