530.二叉搜索树的最小绝对差
题目链接530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
思路
看到题,我想到的是,先中序遍历得到结果数组,因为二叉搜索树遍历得到的数组是有序的
我对前后元素求差值,存放到一个数组,然后再求这个数组的最小值
试一下
可以
提交

python
# 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 getMinimumDifference(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
res=self.traversal(root)
print(res)
minus=[]
for i in range(len(res)-1):
minus.append(res[i+1]-res[i])
return min(minus)
def traversal(self,root: Optional[TreeNode])->List:
if not root:
return []
return self.traversal(root.left)+[root.val]+self.traversal(root.right)
501.二叉搜索树中的众数
题目链接 501. 二叉搜索树中的众数 - 力扣(LeetCode)
思路
其实比较简单的思路,时间复杂度可能更高,但是我现在只求能过,提交通过
我把二叉搜索树这种可以遍历得到数组,然后再进行处理的都这么解决
先遍历,得到数组,统计每个数出现的次数,返回出现次数最多的数。
但是这里有一个难点就是,需要把数字和出现的次数对应记录(字典),然后不是返回次数最多的次数,而是这个次数对应的数字
提交

python
# 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]:
if not root:
return []
nums=self.traversal(root)
count={}
for num in nums:
count[num]=count.get(num,0)+1
max_num=None
max_cnt=0
res=[]
for num,cnt in count.items():
if cnt>max_cnt:
max_cnt=cnt
for num,cnt in count.items():
if max_cnt==cnt:
res.append(num)
return res
def traversal(self,root):
if not root:
return []
return self.traversal(root.left)+[root.val]+self.traversal(root.right)
236. 二叉树的最近公共祖先
题目链接 236. 二叉树的最近公共祖先 - 力扣(LeetCode)
思路
题的意思是大概能看懂,自己看图大概也知道是什么。
但是判断依据不知道怎么写。
p,q这两个节点从底往上遍历,交汇的最近的节点就是他们的最近公共祖先
从下往上(后序)遍历二叉树,分别在左右子树里找 p 和 q:
-
如果左右都找到了,说明当前节点就是最近公共祖先;
-
如果只在一边找到,就把那边的结果往上返回;
-
遇到空节点、p 或 q 就直接返回。


提交

python
# 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==q or root==p or root is None:
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 None and right is not None:
return right
elif left is not None and right is None:
return left
else:
return None