530. Minimum Absolute Difference in BST 501. Find Mode in Binary Search Tree 236. Lowest Common Ance

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

 

BST   -> def inordertraversal!!!!:

# 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.vec = []
        self.inorder_travelsal(root)
        diff = float('inf')
        for i in range(1, len(self.vec)):
            diff = min(diff, (self.vec[i]-self.vec[i-1]))
        return diff

    
    def __init__(self, vec=None, diff=0):
        self.vec = []
        #self.diff = 0
    
    def inorder_travelsal(self,root):
        if not root:#忘记了
            return
        self.inorder_travelsal(root.left)
        self.vec.append(root.val)
        self.inorder_travelsal(root.right)

501. Find Mode in Binary Search Tree (mode众数

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

#基础知识

#find the maxvalue of a dictionary 

max_freq = max(freq_map.values())

#traversal of a dictionary

for key, freq in freq_map.items():

my solution:

# 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]:
        self.vec = []
        self.inoreder_traversal(root)
        count = {}
        result = []
        for v in self.vec: #定义字典有更简单的方法 {key数字:val频率}
            if v not in count:
                count[v] = 1
            else:
                count[v] += 1
        max_freq = max(count.values()) #字典中最大的频率
        for key, freq in count.items(): # 遍历字典,找出所有相同频率的数字
            if freq == max_freq:
                result.append(key)
        return result

    
    def __init__(self, vev=None):
        self.vec = []
    
    def inoreder_traversal(self, root):
        if not root:
            return
        self.inoreder_traversal(root.left)
        self.vec.append(root.val)
        self.inoreder_traversal(root.right)

 using defaultdict:

# 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
from collections import defaultdict

class Solution:
    def searchBST(self, cur, freq_map):
        if cur is None:
            return
        freq_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 result
        self.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. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA)最近公共祖先 of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

 2 coditions that q,p have a lowestcommonancestor:

 

iteration:

# 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: #root和q都是node,不需要再root.val
            return root
        
        left_Ancextor = self.lowestCommonAncestor(root.left, p, q) #左边有q或者p就是True
        right_Ancextor = self.lowestCommonAncestor(root.right, p, q)

        if  left_Ancextor and  right_Ancextor:#递归到这个root时候左右各包含一个p或者q子节点了,这个就是祖先
            return root
        if left_Ancextor and not right_Ancextor:
            return left_Ancextor
        if right_Ancextor and not left_Ancextor:
            return right_Ancextor
        else:
            return None

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值