530 二叉搜索树的最小绝对差
题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
视频讲解:二叉搜索树中,需要掌握如何双指针遍历!| LeetCode:530.二叉搜索树的最小绝对差_哔哩哔哩_bilibili
思路:首先明确中序遍历搜索二叉树可以得到一个有序数组,对二叉树进行中序遍历然后用双指针记录当前值和上一个值,做减法再递归得到最小值
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.result = float('inf') #正无穷 存最小值
self.pre = None #cur的前一个的指针
def traversal(self, cur):
if cur is None:
return #递归终止条件
self.traversal(cur.left) #向左递归
if self.pre is not None:
self.result = min(self.result, cur.val - self.pre.val) #算最小值
self.pre = cur #移动指针
self.traversal(cur.right) #向右递归
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
self.traversal(root)
return self.result
501.二叉搜索树中的众数
题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)
视频讲解:不仅双指针,还有代码技巧可以惊艳到你! | LeetCode:501.二叉搜索树中的众数_哔哩哔哩_bilibili
思路:首先还是利用搜索二叉树的特性,中序遍历可以得到一个有序数组,然后使用双指针
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.max_count = 0 #最大频率
self.count = 0 #当前值频率
self.pre = None #指针
self.result = [] #结果集
def search_Bst(self, cur):
if cur is None: #递归终止条件
return
self.search_Bst(cur.left) #向左递归
if self.pre is None:
self.count = 1
elif self.pre.val == cur.val: #如果当前值和前一个相等,频率加一
self.count += 1
else: #如果当前值也不为空也不跟前一个相等,频率重新为1
self.count = 1
self.pre = cur #更新前一个指针
if self.count == self.max_count: #如果当前值出现频率最高,就把节点值加入结果集
self.result.append(cur.val)
if self.count >self.max_count: #如果当前频率大于最大频率,书信最大频率并更新结果集
self.max_count = self.count
self.result = [cur.val]
self.search_Bst(cur.right) #向右递归
return
def findMode(self, root: Optional[TreeNode]) -> List[int]:
self.max_count = 0
self.count = 0
self.pre = None
self.result = []
self.search_Bst(root)
return self.result
236. 二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)
思路:本题要用后序遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None:
return None
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left is not None and right is not None:
return root
if left is not None and right is None:
return left
if left is None and right is not None:
return right
else:
return None