235.二叉搜索树的最近公共祖先
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
if p.val > q.val:
return self.lowestCommonAncestor(root,q,p)
#现在可以保证两个节点在祖先节点两侧
if root.val >= p.val and root.val <= q.val:
return root
if root.val > q.val: #pq都在左侧
return self.lowestCommonAncestor(root.left,p,q)
else: #都在右侧
return self.lowestCommonAncestor(root.right,p,q)
235.二叉搜索树中的插入操作
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root is None:
return TreeNode(val)
if root.val > val: #那么val只能在左节点中插入
root.left=self.insertIntoBST(root.left,val)
if root.val < val:
root.right=self.insertIntoBST(root.right,val)
return root
450.删除二叉搜索树中的节点
这道题一共有五种情况:
- 根节点为空
- 左节点为空,右节点不为空
- 左节点不为空,右节点为空
- 左右节点都为空
- 左右节点都不为空
其中最后一种情况是最难处理的,在这道题中,我们选择将根节点的左节点放到右子树叶子节点下面(因为是搜索树)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
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