-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathinsert-into-a-binary-search-tree.py
53 lines (45 loc) · 1.33 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
49
50
51
52
53
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
new_node = TreeNode(val)
node = root
parent = None
while node:
parent = node
if node.val < new_node.val:
node = node.right
else:
node = node.left
if not parent:
root = new_node
elif new_node.val < parent.val:
parent.left = new_node
elif new_node.val > parent.val:
parent.right = new_node
else:
pass
return root
def insertIntoBST1(self, root, val):
if not root:
return
node = TreeNode(val)
current_node = root
while True:
if node.val < current_node.val:
if current_node.left:
current_node = current_node.left
else:
current_node.left = node
break
else:
if current_node.right:
current_node = current_node.right
else:
current_node.right = node
break
return root