문제
https://leetcode.com/problems/search-in-a-binary-search-tree/
Search in a Binary Search Tree - LeetCode
Can you solve this real interview question? Search in a Binary Search Tree - You are given the root of a binary search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If
leetcode.com
이진 탐색 트리에서 특정 값을 가진 노드를 찾아 해당 노드를 루트로 하는 서브트리를 반환하는 문제다. (해당 값과 일치하는 노드가 존재하지 않으면 null을 반환)
예시
Example 1:
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Example 2:
Input: root = [4,2,7,1,3], val = 5
Output: []
풀이
# 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 searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return None
# 현재 노드의 값이 찾고자 하는 값과 일치하는 경우, 현재 노드를 반환
if root.val == val:
return root
# 현재 노드의 값이 찾고자 하는 값보다 큰 경우, 왼쪽 서브트리에서 탐색
elif root.val > val:
return self.searchBST(root.left, val)
# 현재 노드의 값이 찾고자 하는 값보다 작은 경우, 오른쪽 서브트리에서 탐색
elif root.val < val:
return self.searchBST(root.right, val)
- 이진 탐색 트리이기 때문에 찾고자 하는 값이 작으면 왼쪽으로, 값이 크면 오른쪽으로 이동하는 특성을 활용하여 효율적으로 탐색할 수 있다.
'알고리즘' 카테고리의 다른 글
[백준(BOJ)] 1922번 네트워크 연결 - 파이썬/python (1) | 2024.01.13 |
---|---|
[리트코드(LeetCode)] 110번 Balanced Binary Tree (0) | 2024.01.13 |
[백준(BOJ)] 11725번 트리의 부모 찾기 (0) | 2024.01.12 |
[리트코드(LeetCode)] 938번 Range Sum of BST (0) | 2024.01.12 |
[리트코드(LeetCode)] 543번 Diameter of Binary Tree (0) | 2024.01.12 |