[LeetCode] 701. Insert into a Binary Search Tree

Chobby·2026년 7월 7일

LeetCode

목록 보기
1106/1111

😎풀이

  1. val이 들어갈 위치를 전위순회하며 재귀호출
  2. 위치를 발견한 경우 TreeNodeval로 초기화하여 생성 및 선언
  3. value가 입력된 이진 탐색 트리 반환
function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
    if(!root) return new TreeNode(val)
    if(root.val > val) root.left = insertIntoBST(root.left, val)
    if(root.val < val) root.right = insertIntoBST(root.right, val)
    return root
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글