235. 二叉搜索树的最近公共祖先
思路:
因为是在二叉搜索树中,所以将node与p,q对比即可,若node.val小于p,q.val,搜索右子树,相反若大于,则搜索左子树
代码:
# 二叉树节点的定义
# 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':
# 定义深度优先搜索函数,用于查找最近公共祖先
def dfs(node, p, q):
# 如果节点为空,返回
if node == None:
return
# 如果节点值大于p和q的值,说明最近公共祖先在左子树中
if node.val > p.val and node.val > q.val:
return dfs(node.left, p, q)
# 如果节点值小于p和q的值,说明最近公共祖先在右子树中
if node.val < p.val and node.val < q.val:
return dfs(node.right, p, q)
# 如果上述条件都不满足,当前节点即为最近公共祖先
return node
# 返回最近公共祖先的结果,初始调用传入根节点和两个目标节点p、q
return dfs(root, p, q)
701.二叉搜索树中的插入操作
代码:
# 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:
node = TreeNode(val)
return node
if root.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