235. 二叉搜索树的最近公共祖先力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
提醒
相对于 二叉树的最近公共祖先 本题就简单一些了,因为 可以利用二叉搜索树的特性。
递归法
class Solution:
def traversal(self, cur, p, q):
if cur is None:
return cur
# 左
if cur.val > p.val and cur.val > q.val:
left = self.traversal(cur.left, p, q)
#中
if left is not None:
return left
# 右
elif cur.val < p.val and cur.val < q.val:
right = self.traversal(cur.right, p, q)
#中
if right is not None:
return right
else:
return cur
def lowestCommonAncestor(self, root, p, q):
return self.traversal(root, p, q)
迭代法
class Solution:
def lowestCommonAncestor(self, root, p, q):
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
return None
701.二叉搜索树中的插入操作 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
递归法
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root is None #为什么不加上or root.val == val: #因为这是搜索二叉树
return TreeNode(val)
elif 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 insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root is None: # 如果根节点为空,创建新节点作为根节点并返回
return TreeNode(val)
cur = root
parent = root # 记录上一个节点,用于连接新节点
while cur is not None:
parent = cur
if cur.val > val:
cur = cur.left
else:
cur = cur.right
node = TreeNode(val)
if val < parent.val:
parent.left = node # 将新节点连接到父节点的左子树
else:
parent.right = node # 将新节点连接到父节点的右子树
return root
450.删除二叉搜索树中的节点 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
提醒
插入操作,本题就有难度了,涉及到改树的结构,把二叉搜索树中删除节点遇到的情况都搞清楚,有以下五种情况:
- 第一种情况:没找到删除的节点,遍历到空节点直接返回了找到删除的节点
- 第二种情况:左空右空(叶子节点),直接删除节点, 返回NULL为根节点
- 第三种情况:删除节点的左为空,右不为空,删除节点,右孩子补位,返回让右孩子为根节点
- 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
- 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
搜索二叉树
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return root
if root.val == key:
if root.left is None and root.right is None:
return None
elif root.left is None:#左空右不空
return root.right
elif root.right is None:#左不空右空
return root.left
else:
cur = root.right
while cur.left is not None:
cur = cur.left
cur.left = root.left
return root.right
#单层逻辑 这里面的root与上面终止条件中的root不相同
if root.val > key:
root.left = self.deleteNode(root.left, key)
if root.val < key:
root.right = self.deleteNode(root.right, key)
return root
普通二叉树(进阶)
二刷再来