代码随想录算法训练营第21天 |Binary Tree|● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先

530. Minimum Absolute Difference in BST

class Solution:
    def __init__(self):
        self.pre = None
        self.res = float('inf')
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        def inorder(root):
            if not root:
                return
            inorder(root.left)
            if self.pre != None:
                self.res = min(self.res, root.val - self.pre)
            self.pre = root.val
            inorder(root.right)
        
        inorder(root)
        return self.res

        
  • two pointers
  • Sol2: use list, 略

501. Find Mode in Binary Search Tree

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.

Sol1: use hash table

class Solution1:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        count_dict = {}
        res = []
        def inorder(root):
            if not root:
                return
            inorder(root.left)
            count_dict[root.val]=count_dict.get(root.val,0)+1
            inorder(root.right)
        inorder(root)
        max_v = max(count_dict.values())
        for x in count_dict.keys():
            if count_dict[x] == max_v:
                res.append(x)
        return res

Sol2: two pointers

class Solution:
    #only appears in nearby nodes
    def __init__(self):
        self.pre_value = None
        self.res = []
        self.count = 0
        self.max_count = 0
    def findMode(self, root: Optional[TreeNode]) -> List[int]:

        def inorder(root):
            if not root:
                return
            inorder(root.left)
            if self.pre_value == None:
                self.count = 1
            elif self.pre_value == root.val:
                self.count+=1
            else:
                self.count = 1

            self.pre_value = root.val

            #print(count, max_count)
            if self.count== self.max_count:
                self.res.append(root.val)
            if self.count > self.max_count:
                self.res = [root.val]
                self.max_count = self.count
            inorder(root.right) 

        inorder(root)
        return self.res

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).”

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root:
            return None
        
        if root == p or root == q:
            return root
        
        left = self.lowestCommonAncestor(root.left,p,q)
        right = self.lowestCommonAncestor(root.right,p,q)

        if left and right:
            return root
        elif left and not right:
            return left
        elif not left and right:
            return right
        else:
            return None
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值