题目链接:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == None:
return root
if root.val > p.val and root.val > q.val:
left = self.lowestCommonAncestor(root.left, p, q)
if left != None:
return left
if root.val < p.val and root.val < q.val:
right = self.lowestCommonAncestor(root.right, p, q)
if right != None:
return right
return root
题目链接:701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
思路:很简单,val比当前节点大,往右找,val比当前节点小,往左找;直到找到None,并记录pre,再插入。
class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
index = root
pre = None
while index != None:
pre = index
if val > index.val:
index = index.right
else:
index = index.left
if pre == None:
return TreeNode(val)
if pre.val > val:
pre.left = TreeNode(val)
else:
pre.right = TreeNode(val)
return root
题目链接:450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
第一次用迭代没做出来,思路是正确的,但是处理不好;看了代码随想录写出的答案
class Solution:
def deleteNode(self, root, key):
if root is None:
return root
if root.val == key:
if root.left is None and root.right is None:
return None
elif root.left is None:
return root.right
elif root.right is None:
return root.left
else:
cur = root.right
while cur.left is not None:
cur = cur.left
cur.left = root.left
return root.right
if root.val > key:
root.left = self.deleteNode(root.left, key)
if root.val < key:
root.right = self.deleteNode(root.right, key)
return root