[LeetCode#108] Convert Sorted Array to Binary Search Tree

2024. 9. 25. 11:50·Algorithm/문제풀이

❒ Description


날짜 2024.09.25 (수)
레벨 Easy
제목 Convert Sorted Array to Binary Search Tree
링크 https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
자료구조 그래프 - BST
시간 복잡도 O(n)

이번 문제는 BST의 특징을 정확하게 파악하고 있어야 한다.

 

 

 

 

 

❒ Solution


public TreeNode sortedArrayToBST(int[] nums) {
    return construct(nums, 0, nums.length - 1);
}

public TreeNode construct(int[] nums, int lo, int hi) {
    if (lo > hi) return null;
    int mid = lo + (hi - lo) / 2;
    TreeNode node = new TreeNode(nums[mid]);
    node.left = construct(nums, lo, mid - 1);
    node.right = construct(nums, mid + 1, hi);
    return node;
}

배열의 중앙 값을 구하고, 그 중앙 값을 기준으로 좌,우의 배열을 재귀로 순환하면서 해결하는 방법이다.

`int mid = lo + (hi - lo) / 2`에서 lo를 더해주는 이유는 쪼개진 배열의 가장 앞 index를 기준으로 하기 위해서다.

 

 

 

 

 


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

[LeetCode#938] Range Sum of BST  (0) 2024.09.25
[LeetCode#1038] Binary Search Tree to Greater Sum Tree  (0) 2024.09.25
[LeetCode#310] Minimum Height Trees  (0) 2024.09.24
[LeetCode#110] Balanced Binary Tree  (0) 2024.09.23
[LeetCode#] Invert Binary Tree  (0) 2024.09.22
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#938] Range Sum of BST
  • [LeetCode#1038] Binary Search Tree to Greater Sum Tree
  • [LeetCode#310] Minimum Height Trees
  • [LeetCode#110] Balanced Binary Tree
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (173)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (4)
        • Java (3)
        • Kotlin (1)
      • 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 (7)
        • 이벤트 기반 마이크로서비스 구축 (6)
        • 친절한 SQL 튜닝 (1)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#108] Convert Sorted Array to Binary Search Tree
상단으로

티스토리툴바