[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

Categories:

Updated:

Leave a comment