235. 二叉搜尋樹的最近公共祖先
因為是搜尋二叉樹,所以只要值在q和p之間,那麼就是lowest common ancestor
# 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 root is None:
return None
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
if root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
return root
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:
return TreeNode(val)
elif root.val > val:
root.left = self.insertIntoBST(root.left, val)
elif root.val < val:
root.right = self.insertIntoBST(root.right, val)
return root
450.刪除二叉搜尋樹中的節點
怎麼刪除一個根結點,將它的值和right subtree的最左葉子的值交換,然後刪除最左葉子
# 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 None
if root.val == key:
if root.right is None:
return root.left
cur = root.right
while cur.left:
cur = cur.left
cur.val, root.val = root.val, cur.val
root.left = self.deleteNode(root.left, key)
root.right = self.deleteNode(root.right, key)
return root