tasks for today:
1. 530.二叉搜索树的最小绝对差
2. 501.二叉搜索树中的众数
3. 236.二叉树的最近公共祖先
-----------------------------------------------------------------
1. 530.二叉搜索树的最小绝对差
in this practice, the target tree is a binary search tree, which makes it have a special feature that its inorder is an ascending list, so we can first get the inorder list for the binary search tree and then go throught the list recoridng the min_val.
# 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:# get inorder list, which get the inscending order listresult = []def inorder_travese(node):if not node:return Noneinorder_travese(node.left)result.append(node.val)inorder_travese(node.right)inorder_travese(root)min_val = float('inf')for i in range(1, len(result)):if result[i] - result[i-1] < min_val:min_val = result[i] - result[i-1]return min_val
2. 501.二叉搜索树中的众数
This practice, a defaultdict can be used to calculate the frequency of the showup for a tree node's value:
# 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]:calcu = collections.defaultdict(int)nodeQueue = collections.deque([root])while nodeQueue:cur = nodeQueue.popleft()calcu[cur.val] += 1if cur.left:nodeQueue.append(cur.left)if cur.right:nodeQueue.append(cur.right)max_num = max(calcu.values())result = []for key, value in calcu.items():if value == max_num:result.append(key)return result
In this practice, the above method is a general solution which works for all types of tress, but if the tree is a not normal binary tree, instead a binary search tree, there is also other solutions which is incented by the binary search tree's feature that the inorder list is an asceding list.
this method use double pointers, similar with 530.
3. 236.二叉树的最近公共祖先
this practice is a bit challenging, the tutorial include a summary for sorting when the recursive has return value.
# 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 is None:return rootleft = self.lowestCommonAncestor(root.left, p, q)right = self.lowestCommonAncestor(root.right, p, q)if left and right: return rootelif not left and right: return rightelif left and not right: return leftelse: return None