반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 701 | Insert into a Binary Search Tree | Python 본문
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
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 290 | Word Pattern | Python (0) | 2022.01.17 |
---|---|
[LeetCode] 452 | Minimum Number of Arrows to Burst Balloons | Python (0) | 2022.01.13 |
[LeetCode] 67 | Add Binary | Python (0) | 2022.01.10 |
[LeetCode] 1094 | Car Pooling | Python (0) | 2022.01.06 |
[LeetCode] 131 | Palindrome Partitioning | Python (0) | 2022.01.05 |
Comments