Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 04b285e

Browse files
authored
Update Insert_into_Binary_Search_Tree.py
1 parent e88eb19 commit 04b285e

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

‎Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
# Time: O(N) and Space: O(1)
2-
1+
""" Time: O(N) and Space: O(1) """
2+
# Iterative Solution
33
class Solution:
44
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
55
if root is None:
@@ -22,3 +22,14 @@ def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode
2222

2323
return root
2424

25+
26+
# Recursive Solution
27+
class Solution:
28+
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
29+
if root is None:
30+
root = TreeNode(val)
31+
elif root.val < val:
32+
root.right = self.insertIntoBST(root.right, val)
33+
else:
34+
root.left = self.insertIntoBST(root.left, val)
35+
return root

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /