작심삼일

[LeetCode] 701 | Insert into a Binary Search Tree | Python 본문

스터디/코테

[LeetCode] 701 | Insert into a Binary Search Tree | Python

yun_s 2022. 1. 12. 09:48
728x90
반응형

문제 링크: https://leetcode.com/problems/insert-into-a-binary-search-tree/


문제

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.


조건

  • The number of nodes in the tree will be in the range [0, $10^4$].
  • $-10^8$ <= Node.val <= $10^8$
  • All the values Node.val are unique.
  • $-10^8$ <= val <= $10^8$
  • It's guaranteed that val does not exist in the original BST.

내 풀이

BST에 새로운 값을 삽입하는 기본적인 문제다.

root보다 작으면 왼쪽으로, root보다 크면 오른쪽으로 진행하는 것을 반복하면 된다.


코드

# 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 insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root:
            root = TreeNode(val)
        else:
            self.insert(root, val)
        return root
        
    def insert(self, root, val):
        if root.val > val:
            if root.left:
                self.insert(root.left, val)
            else:
                root.left = TreeNode(val)
        elif root.val < val:
            if root.right:
                self.insert(root.right, val)
            else:
                root.right = TreeNode(val)
728x90
반응형
Comments