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 common(self,cur,p,q):
if not cur:
return None
if cur.val>p.val and cur.val>q.val:
left=self.common(cur.left,p,q)
if left is not None:
return left
if cur.val<p.val and cur.val<q.val:
right=self.common(cur.right,p,q)
if right is not None:
return right
return cur
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
return self.common(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 not root:
return TreeNode(val)
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.删除二叉搜索树中的节点
第一种情况:没找到删除的节点,遍历到空节点直接返回了
找到删除的节点
第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
# 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 not root:
return root
if root.val==key:
if root.left==None and root.right==None:
#注意nonetype没有val属性
return None
elif root.left==None:
return root.right
elif root.right==None:
return root.left
else:
cur=root.right
while cur.left:
cur=cur.left
cur.left=root.left
return root.right
root.left=self.deleteNode(root.left,key)
root.right=self.deleteNode(root.right,key)
return root