235. 二叉搜索树的最近公共祖先
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解:代码随想录
视频讲解:二叉搜索树找祖先就有点不一样了!| 235. 二叉搜索树的最近公共祖先_哔哩哔哩_bilibili
解题思路:
利用二叉搜索树的特性 值小于当前node值的都在左边 值大于当前node值的都在右边。
当pq的值都小于node值时向左递归 反之向右,如果都不符合条件 说明一大一小 我们找到了最小的公共祖先 直接返回结果
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left,p,q)
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right,p,q)
return root
701.二叉搜索树中的插入操作
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解:代码随想录
视频讲解:原来这么简单? | LeetCode:701.二叉搜索树中的插入操作_哔哩哔哩_bilibili
解题思路:
设置basic condition 如果root为空直接返回node
如果val小于root的值 那么val应该放在左边 进入左递归 反之 进入右递归
最后返回root作为答案
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
node= TreeNode(val)
if not root: return node
if val < root.val:
root.left = self.insertIntoBST(root.left, val)
if val > root.val:
root.right = self.insertIntoBST(root.right, val)
return root
450.删除二叉搜索树中的节点
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解:代码随想录
视频讲解:调整二叉树的结构最难!| LeetCode:450.删除二叉搜索树中的节点_哔哩哔哩_bilibili
解题思路:
首先确认root不为空 如果为空直接返回。
然后我们要找到目标key 如果root的值大于key 进入左递归 反之进入右递归 剩下的情况则是我们找到了目标key, 此时 我们要分成五种情况:
1. 没有左右子树 我们return 空就好
2. 没有左子树 我们return 右子树就好
3. 没有右子树 我们return 左子树就好
4. 两个都有 我们可以找到当前右子树中最靠左的leaf节点 并将当前左子树 挂在这个节点 再return右子树。
最后记得返回root
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root:
return root
if root.val > key:
root.left = self.deleteNode(root.left,key)
elif root.val < key:
root.right = self.deleteNode(root.right,key)
else:
if not root.left and not root.right:
return None
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
return root