题目描述
Category:Medium Tree
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
题目理解
给定一棵二叉搜索树和一个值,返回插入该节点后的二叉搜索树的根节点。可能会有多种插入方式,返回任意一种即可。
注:该值在原二叉搜索树中不存在。
解题思路
迭代
实现思路和递归类似,若根节点为空,新建节点返回。然后用一个变量cur来遍历,若当前节点值大于插入值,判断它的左子节点是否为空,若为空,新建节点并跳出循环,否则继续遍历左子树;反之亦然。
思路借鉴:https://www.cnblogs.com/grandyang/p/9914546.html
class Solution:
# Runtime: 136ms 85.17% MemoryUsage: 16MB 8.00%
def insertIntoBST1(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
return TreeNode(val)
cur_node = root
while True:
if cur_node.val > val:
if cur_node.left is None:
cur_node.left = TreeNode(val)
break
cur_node = cur_node.left
else:
if cur_node.right is None:
cur_node.right = TreeNode(val)
break
cur_node = cur_node.right
return root
MyMethod
递归,再加上二叉搜索树的特性:若插入值大于根节点的值,将该值插入在右子树中;若小于,则左子树。
class Solution:
# Runtime: 144ms 36.95% MemoryUsage: 15.1MB 100.00%
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
new_node = TreeNode(val)
root = new_node
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
elif root.val < val:
root.right = self.insertIntoBST(root.right, val)
return root
Time
2020.3.28 今天要更加努力呀!