530.二叉搜索树的最小绝对差
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
解题思路:
利用pre,cur进行对比,进行中序遍历,形成的遍历数组是递增关系,进行前后对比即可。
输入参数:def dfs(self, cur)
停止条件:if not cur: return None
递归逻辑:def(root.left), if pre, result = min(result, abs(cur.val-pre.val)),设置pre = cur
# 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
def dfs(self, cur):
if not cur:
return None
self.dfs(cur.left)
if self.pre:
self.result = min(self.result, abs(cur.val - self.pre.val))
self.pre = cur
self.dfs(cur.right)
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
self.dfs(root)
return self.result
501.二叉搜索树中的众数
给你一个含重复值的二叉搜索树(BST)的根节点 root
,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
解题思路:
本题依然使用中序遍历,设定初始count=0,max_count = 0, result = [], pre = None,遍历到中间节点时,检查是否在叶子节点,直接count=1,如果pre=cur,说明有重复节点,count += 1,否则就是新的节点但是不重复,count = 1。重要的是要更新max_count,当max_count小于count,更新并且清空result,加上新的cur,count=max_max_count说明当前cur应添加进result。
# 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 findMode(self, root: Optional[TreeNode]) -> List[int]:
count = 0
max_count = 0
pre = None
result = []
def dfs(cur):
nonlocal pre, max_count, result, count
if not cur:
return None
dfs(cur.left)
if not pre:
count = 1
elif cur.val == pre.val:
count += 1
else:#前后不同
count = 1
pre = cur
if max_count == count:
result.append(cur.val)
if max_count<count:
max_count = count
result = []
result.append(cur.val)
dfs(cur.right)
dfs(root)
return result
236. 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
解题思路:
本题需要使用回溯,后序遍历满足要求,判断左右子树是否包含p或q,有的话返回root,否则返回None
确认输入参数:def isCommon(root, p, q)
停止条件:if not root, return root; if root == p or root == q: return root
递归逻辑:left,right分别递归,便利中间节点时如果左右都有,返回root,只有左边有,返回左边,只有右边有,返回右边。
# 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 not root:
return root
if root == p or root == q:
return root#return root if existed
left = self.lowestCommonAncestor(root.left, p,q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
elif left and not right:
return left
elif right and not left:
return right