235. 二叉搜索树的最近公共祖先
二叉搜索树自带方向性,搜索时不需要考虑前中后序
递归法
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
if root == p or root == q:
return root
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
elif root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
else:
return root
迭代法
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:
break
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:
root.left = self.insertIntoBST(root.left, val)
elif root.val < val:
root.right = self.insertIntoBST(root.right, val)
return root
迭代法:
二叉树本质是链表,插入删除要记前后节点
class Solution:
def __init__(self):
self.parent = None
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
cur = root
# 都可以插在叶子结点上
while cur:
self.parent = cur
if cur.val > val:
cur = cur.left
elif cur.val < val:
cur = cur.right
if self.parent.val > val:
self.parent.left = TreeNode(val)
else:
self.parent.right = TreeNode(val)
return root
450.删除二叉搜索树中的节点
二叉搜索树
class Solution:
def deleteNode(self, node: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not node:
return None
if node.val == key:
if not node.left and node.right:
return node.right
elif node.left and not node.right:
return node.left
elif not node.left and not node.right:
return None
else:
# 放右子树,左子树放在右子树最左边
cur = node.right
while cur.left:
cur = cur.left
cur.left = node.left
return node.right
elif node.val < key:
node.right = self.deleteNode(node.right, key)
else:
node.left = self.deleteNode(node.left, key)
return node