题目
思路
从左右子树中不断寻找合适的位置插入即可。
代码
"""
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
currNode = root
if not root:
return node
while currNode:
if node.val < currNode.val:
if not currNode.left:
currNode.left = node
return root
else:
currNode = currNode.left
elif node.val > currNode.val:
if not currNode.right:
currNode.right = node
return root
else:
currNode = currNode.right