235. 二叉搜索树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or (root.val <= p.val and root.val >= q.val) or (root.val >= p.val and root.val <= q.val):
return root
if root.val < p.val and root.val < q.val:
result = self.lowestCommonAncestor(root.right, p, q)
if result:
return result
if root.val > p.val and root.val > q.val:
result = self.lowestCommonAncestor(root.left, p, q)
if result:
return result
701.二叉搜索树中的插入操作
https://programmercarl.com/0701.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E6%8F%92%E5%85%A5%E6%93%8D%E4%BD%9C.html#%E6%80%9D%E8%B7%AF
遍历整棵搜索树简直是对搜索树的侮辱
利用搜索树的有序性,根据节点与待插入值的大小关系遍历左子树或者右子树,遇到第一个空节点进行插入
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
root = TreeNode(val)
return root
self.insert(root,val)
return root
def insert(self, node, val):
if node.val < val:
if node.right:
self.insert(node.right,val)
if not node.right:
node.right = TreeNode(val)
return
if node.val > val:
if node.left:
self.insert(node.left,val)
if not node.left:
node.left = TreeNode(val)
return
450.删除二叉搜索树中的节点
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return root
if root.val == key:
if not root.left and not root.right:
return None
elif not root.left:
return root.right
elif not root.right:
return root.left
else:
node = root.right
while node.left:
node = node.left
node.left = root.left
return root.right
if root.val < key:
root.right = self.deleteNode(root.right, key)
elif root.val > key:
root.left = self.deleteNode(root.left, key)
return root