[LeetCode] 701. Insert into a Binary Search Tree
Updated:
701. Insert into a Binary Search Tree
μμ νμλ μ΄μ§νμνΈλ¦¬ λ§λλ λ¬Έμ μ λκ°μ μ νμ΄λ€. LeetCode λ¬Έμ λ₯Ό νλ©΄μ λλ λͺ¨λ₯΄κ² λ€μλ μ΅κ΄μ΄ μλ€.
λ°λ‘ Solution ν΄λμ€μ ν¨μκ° μ£Όμ΄μ§λ©΄ κ·Έ μμλ€ λλ§μ ν¨μλ₯Ό λ§λ€μ΄ νμλ€.
λ κ·Έλλ ν리면 μκ΄μ μκ² λ€λ§ μ¬κ·κ°μ λΆλΆμμ λκ° κΌ¬μ΄λ λΆλΆμ΄ μ’ μμλ€. κ·Έλ₯ μ£Όλλλ‘ κ·Έ ν¨μ μ¨μ νλ €κ³ λ Έλ ₯ν΄μΌκ² λ€.
μ΄ λ¬Έμ λ κ²μ ν¨μμμ μ¬κ·λ‘ λλ©΄ μμ£Ό κ°λ¨ν ν μ μμΌλκΉ..
# 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: TreeNode, val: int) -> TreeNode:
if root is None:
return TreeNode(val)
if val < root.val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root
Leave a comment