代码随想录刷题第二十二天
二叉搜索树的最近公共祖先 (LC 235) 简单
题目思路:
代码实现:
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None:
return None
if root.val < p.val and root.val < q.val:
left = self.lowestCommonAncestor(root.right, p, q)
if left is not None:
return left
elif root.val > q.val and root.val > p.val:
right = self.lowestCommonAncestor(root.left, p, q)
if right is not None:
return right
else:
return root
二叉搜索树的插入操作 (LC 701) 简单
题目思路:
代码实现:
class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
if root is None:
newnode = TreeNode(val)
return newnode
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
if root.val < val:
root.right = self.insertIntoBST(root.right, val)
return root
删除二叉搜索树中的节点 (LC 450) 困难
题目思路:
代码实现:
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if root is None:
return None
if root.val == key:
if root.left is None and root.right is None:
return None
elif root.left is not None and root.right is None:
return root.left
elif root.left is None and root.right is not None:
return root.right
else:
return self.constructsubtree(root.right, root.left)
else:
root.left = self.deleteNode(root.left, key)
root.right = self.deleteNode(root.right, key)
return root
def constructsubtree(self, rightroot, leftroot):
if rightroot is None:
return leftroot
rightroot.left = self.constructsubtree(rightroot.left, leftroot)
return rightroot