-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinsert-into-a-binary-search-tree.py
48 lines (41 loc) · 1.49 KB
/
insert-into-a-binary-search-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from typing import Optional
# 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:
# iterative solution
# Time complexity: O(log n) in a balanced tree, otherwise O(n)
# Space complexity: O(1)
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: return TreeNode(val)
curr = root
while True:
if val < curr.val:
if curr.left:
curr = curr.left
else:
curr.left = TreeNode(val)
break
else:
if curr.right:
curr = curr.right
else:
curr.right = TreeNode(val)
break
return root
# recursive solution
# Time complexity: O(log n) in a balanced tree, otherwise O(n)
# Space complexity: O(log n) for the stack in a balanced tree, otherwise, O(n)
def insertIntoBST2(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
def insert(node, val):
if not node:
return TreeNode(val)
if val > node.val:
node.right = insert(node.right, val)
else:
node.left = insert(node.left, val)
return node
return insert(root, val)