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
标签:None,right,val,root,self,二叉,搜索,树中,left
From: https://www.cnblogs.com/miramira/p/18125744