530. 二叉搜索树的最小绝对差
题目
思路与解法
第一想法: 一个二叉搜索树的最小绝对差,从根结点看,它的结点与它的最小差值一定出现在 左子树的最右结点(左子树最大值)和右子树的最左结点(右子树的最小值)。
这样搞复杂了,直接层序遍历,然后后值减前值,记录最小值
# 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:self.inorder_list = []self.inorder(root)res = float('inf')for i in range(len(self.inorder_list)-1):cur = self.inorder_list[i+1] - self.inorder_list[i]res = cur if cur < res else resreturn resdef inorder(self,root):if not root:returnself.inorder(root.left)self.inorder_list.append(root.val)self.inorder(root.right)
501.二叉搜索树中的众数
题目
思路与解法
第一想法: 遍历
# 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]:from collections import defaultdictclass Solution:def searchBST(self, cur, freq_map):if cur is None:returnfreq_map[cur.val] += 1 # 统计元素频率self.searchBST(cur.left, freq_map)self.searchBST(cur.right, freq_map)def findMode(self, root):freq_map = defaultdict(int) # key:元素,value:出现频率result = []if root is None:return resultself.searchBST(root, freq_map)max_freq = max(freq_map.values())for key, freq in freq_map.items():if freq == max_freq:result.append(key)return result
236. 二叉树的最近公共祖先
题目
思路与解法
carl的讲解: 如果左右都有返回值,那就是它。不可能出现第二个左右都有返回值的节点,因为本题树中节点不重复。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution:def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':if root == p or root == q or root == None:return rootleft = self.lowestCommonAncestor(root.left, p, q)right = self.lowestCommonAncestor(root.right, p, q)if left and right:return rootif not left and right:return rightelif left and not right:return leftelse:return None