-
Notifications
You must be signed in to change notification settings - Fork 90
/
Insert Node in a Binary Search Tree.py
72 lines (51 loc) · 1.35 KB
/
Insert Node in 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a
valid binary search tree.
Example
Given binary search tree as follow:
2
/ \
1 4
/
3
after Insert node 6, the tree should be:
2
/ \
1 4
/ \
3 6
Challenge
Do it without recursion
"""
__author__ = 'Danyang'
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
def insertNode(self, root, node):
"""
Insertion without balance should be straightforward
:param root: The root of the binary search tree.
:param node: insert this node into the binary search tree.
:return: The root of the new binary search tree.
"""
cur = root
if not root:
root = node
return root
while cur:
if cur.val == node.val:
return root
elif cur.val > node.val:
if cur.left:
cur = cur.left
else:
cur.left = node
return root
else:
if cur.right:
cur = cur.right
else:
cur.right = node
return root