LintCode Q85 Insert Node in a Binary Search Tree in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2017年1月28日
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
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@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.
"""
def insertNode(self, root, node):
# write your code here
if root is None:
return node
current = root
while current:
if node.val <= current.val:
if current.left is None:
current.left = node
break
else:
current = current.left
continue
else:
if current.right is None:
current.right = node
break
else:
current = current.right
continue
return root
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。