力扣235.二叉搜索树的最近公共祖先 【medium】
力扣701.二叉搜索树的插入操作 【medium】
力扣450.删除二叉搜索树中的节点【medium】
一、力扣235.二叉搜索树的最近公共祖先【medium】
题目链接:力扣235.二叉搜索树的最近公共祖先
文档链接:代码随想录
1、思路
- 要利用二叉搜索树有序的性质
- 题目说了p、q都在树中,所以我们可以通过遍历往下缩小范围
- 这边不用判断空节点,因为pq的存在性和树的有序性,所以这边不会递归到空节点
- 时间复杂度: O ( n ) O(n) O(n)
2、代码
python
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
x = root.val
if x < p.val and x < q.val:
return self.lowestCommonAncestor(root.right, p, q)
if x > p.val and x > q.val:
return self.lowestCommonAncestor(root.left, p , q)
return root
二、力扣701.二叉搜索树的插入操作【medium】
题目链接:力扣701.二叉搜索树的插入操作
文档链接:代码随想录
1、思路
- 可以不改变树的结构,这样这道题就简单了
- 通过比较
- 时间复杂度: O ( n ) O(n) O(n)
2、代码
python
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)
if root.val < val:
root.right = self.insertIntoBST(root.right , val)
return root
三、力扣450.删除二叉搜索树中的节点【medium】
题目链接:力扣450.删除二叉搜索树中的节点
文档链接:代码随想录
1、思路
- 遍历中寻找
key
,并不全遍历 - 删除节点的操作在终止条件
- 好好理解终止条件的return和最后的return root,这个过程中它就删除了目标节点并且把目标节点的孩子接向了它的父亲
- 时间复杂度: O ( n ) O(n) O(n)
2、代码
python
class Solution:
def deleteNode(self, root, key):
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
if root.val > key:
root.left = self.deleteNode(root.left, key)
if root.val < key:
root.right = self.deleteNode(root.right, key)
return root