235. 二叉搜索树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == p or root == q or root is None:
return root
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
可以省略终止条件判断
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
701.二叉搜索树中的插入操作
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
if root.val > 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
其实上面的解法是无返回值的,只是混在一起了,可以拆开
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
self.traversal(root, val)
return root
def traversal(self, node, val):
if node.val > val:
if not node.left:
node.left = TreeNode(val)
else:
self.traversal(node.left, val)
else:
if not node.right:
node.right = TreeNode(val)
else:
self.traversal(node.right, val)
有返回值能简化程序
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)
else:
root.right = self.insertIntoBST(root.right, val)
return root
450.删除二叉搜索树中的节点
五种情况
未找到
1、没有找到,直接返回空
找到了
2、叶子节点,直接删除
3、左子树为空,右子树存在,右子树替上
4、左子树存在,右子树为空,左子树替上
5、左右子树都不为空,则将左子树放在右子树最左侧的叶子节点上,然后右子树替上
有返回值的写法
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return None
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
if root.val > key:
root.left = self.deleteNode(root.left, key)
if root.val < key:
root.right = self.deleteNode(root.right, key)
return root