701. Insert into a Binary Search Tree

양성준·2025년 5월 21일

코딩테스트

목록 보기
61/102

문제

https://leetcode.com/problems/insert-into-a-binary-search-tree/description/

풀이

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) {
            return new TreeNode(val);
        }
        if(val < root.val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}
  • root.val 보다 작다면 왼쪽으로 이동, 크다면 오른쪽으로 이동
  • root == null, 즉 탐색이 다 끝났다면 거기가 TreeNode(val)의 위치
  • 마지막으로 root를 반환해서 부모노드의 root.left나 root.right에 서브트리를 붙여나감
profile
백엔드 개발자

0개의 댓글