99클럽 코테 스터디 13일차 TIL | Search in a Binary Search Tree

fever·2024년 8월 3일
0

99클럽 코테 스터디

목록 보기
13/42
post-thumbnail

🛠️ 문제

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 such a node does not exist, return null.

💻 풀이

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        // 루트가 null이거나 루트의 값이 찾는 값과 같으면 루트를 반환
        if (root == null || root.val == val) {
            return root;
        }
        
        // 찾는 값이 루트의 값보다 작으면 왼쪽 서브 트리에서 검색
        if (val < root.val) {
            return searchBST(root.left, val);
        }
        
        // 찾는 값이 루트의 값보다 크면 오른쪽 서브 트리에서 검색
        return searchBST(root.right, val);
    }
}

이진트리 특성만 알면 쉽게 풀 수 있는 문제였다. 그래서 큰 고민없이 오분만에 쓴 듯 ㅎ.... 왼쪽이 작고, 오른쪽이 크다는 속성으로 반복하는 것이니 3가지의 경우의 수만 두면 뚝딱 해결 완료~

🤔 고찰

정처기에서 보던 이진트리를 코테에서 만나니 반가웠다.
하지만 처음엔 막상 문제가 영어여서 ...? 이러고 당황하면서 보던 건 비밀...

profile
선명한 삶을 살기 위하여

0개의 댓글