LeetCode.235 二叉搜索树的最近公共祖先
后序遍历
if not root: return
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if p.val < root.val and q.val < root.val: return left
if p.val > root.val and q.val > root.val: return right
return root
LeetCode.701 二叉搜索树中的插入操作
前序遍历
if not root: return TreeNode(val)
if val < root.val:
if not root.left:
root.left = TreeNode(val)
else:
self.insertIntoBST(root.left, val)
else:
if not root.right:
root.right = TreeNode(val)
else:
self.insertIntoBST(root.right, val)
return root
LeetCode.450 删除二叉搜索树中的节点
前序遍历
if not root: return
if root.val == key:
if not root.left and not root.right: return
if not root.left: return root.right
if not root.right: return root.left
node = root.right
while node.left:
node = node.left
node.left = root.left
return root.right
if key < root.val:
root.left = self.deleteNode(root.left, key)
else:
root.right = self.deleteNode(root.right, key)
return root