# 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':
return self.lowestCommonAncestor1(root, p, q)
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 二叉搜索树,是有序的,不同于二叉树的公共祖先需要从下往上遍历
# 而且公共节点一定会出现在【p,q】之前,我们递归遍历,最先出现在这个区间就是公共祖先节点了
if root is None:
return root
# 处理中节点了
if root.val > q.val and root.val > p.val: # 处理左节点
left = self.lowestCommonAncestor(root.left, p, q)
if left is not None:
# if not left: 这种用来判断节点不对的!
return left
if root.val < q.val and root.val < p.val:
right = self.lowestCommonAncestor(root.right, p, q)
if right is not None:
return right
return root
# 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)
# root = node
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
这里就把二叉搜索树中删除节点遇到的情况都搞清楚。
有以下五种情况:
第五种情况有点难以理解,看下面动画:
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