235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
##基础解法
# 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 not root or root==p or root==q:
return root
lf=self.lowestCommonAncestor(root.left,p,q)
rg=self.lowestCommonAncestor(root.right,p,q)
if not lf and not rg:
return None
elif lf and not rg:
return lf
elif not lf and rg:
return rg
else:
return root
# 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':
while root:
if root.val>p.val and root.val>q.val:
root=root.left
elif root.val<p.val and root.val<q.val:
root=root.right
else:
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]:
nw=TreeNode(val=val)
if not root:
return nw
if val>root.val:
root.right=self.insertIntoBST(root.right,val)
if val<root.val:
root.left=self.insertIntoBST(root.left,val)
return root
450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
# 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 not root.left and not root.right:
return None
elif root.left and not root.right:
return root.left
elif not root.left and root.right:
return root.right
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