530.二叉搜索树的最小绝对差
530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
思路:这道题是利用二叉搜索树的性质,所以可以利用昨天学过的,构造一个完整数组,因为这个数组是递增的数组,所以遍历一遍这个数组就可以找到最小绝对差了。这道题还可以用双指针,不过下一题和这题主要思路一致,双指针的方法就用在下一道题了
# 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 getMinimumDifference(self, root):
"""
:type root: Optional[TreeNode]
:rtype: int
"""
vec=[]
def dfs(cur):
if not cur:
return
dfs(cur.left)
vec.append(cur.val)
dfs(cur.right)
dfs(root)
min_val=float('inf')
for i in range(1,len(vec)):
tmp=vec[i]-vec[i-1]
if tmp<min_val:
min_val=tmp
return min_val
501.二叉搜索树中的众数
思路:因为二叉搜索树的性质,所以数值相同的节点在中序遍历中必然相邻,所以只需要用一个指针存放pre前一个节点,然后比较一下当前的值和pre是否相同,如果相同,就cnt+1,不相同就cnt=1.不过这道题有几个地方得注意,一个是python中作用域导致同时在定义的函数内外修改同一个变量会报错,要加上self,还有一个就是这道题的众数可能有很多个,所以如果频率变大了,需要把原来的结果清空。
# 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 findMode(self, root):
"""
:type root: Optional[TreeNode]
:rtype: List[int]
"""
self.cnt_max=0
self.pre=None
self.cnt=0
self.val=[]
def dfs(cur):
if not cur:
return
dfs(cur.left)
if self.pre==None:
self.cnt=1
elif cur.val!=self.pre.val:
self.cnt=1
else:
self.cnt+=1
if self.cnt==self.cnt_max:
self.val.append(cur.val)
elif self.cnt>self.cnt_max:
self.val=[cur.val]
self.cnt_max=self.cnt
self.pre=cur
dfs(cur.right)
return
dfs(root)
return self.val
236. 二叉树的最近公共祖先
236. 二叉树的最近公共祖先 - 力扣(LeetCode)
思路:寻找公共祖先可以想到使用回溯,那就想一下return的条件是什么。那就是如果是None或者是q或者是p,返回值就是这个节点。而回溯的时候还要想一个事情,就是对左右递归的返回值都要使用,否则如果只判断了一个就返回,会导致可能另一边也找到了被淹没掉。处理的方法就是如果两个只有左或者右返回不为空,那就取这个返回值,如果都不为空,那就返回目前的节点
# 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
"""
def dfs(cur):
if cur is None or cur==p or cur==q:
return cur
left=dfs(cur.left)
right=dfs(cur.right)
if left!=None and right!=None:
return cur
elif left!=None and right is None:
return left
elif left is None and right!=None:
return right
else:
return None
return dfs(root)

1万+

被折叠的 条评论
为什么被折叠?



