Leetcode刷题笔记1 二叉树part06

leetcode 530 二叉树的最小绝对差

目前对于代码掌握程度还太低,所以对于一个题目的思路先从会用的方法想思路,比如暴力解法

对于二叉树的最小绝对差,因为是二叉搜索树,所以用中序遍历转为有序数组,然后求取差值

class Solution:
    def __init__(self):
        self.vec = []
    def traversal(self, root):
        if not root:
            return 
        self.traversal(root.left)
        self.vec.append(root.val)
        self.traversal(root.right)
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        self.traversal(root)
        if len(self.vec) < 2:
            return 0
        result = float('inf')
        for i in range(1, len(self.vec)):
            result = min(result, self.vec[i] - self.vec[i - 1])
        return resul

leetcode 501 二叉搜索树中的众数

迭代&字典:

class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        freq = defaultdict(int)
        result = []
        if not root:
            return result
        self.searchBST(root, freq)
        max_freq = max(freq.values())
        for key, value in freq.items():
            if value == max_freq:
                result.append(key)
        return result
    def searchBST(self, cur, freq):
        if not cur:
            return
        freq[cur.val] += 1
        self.searchBST(cur.left, freq)
        self.searchBST(cur.right, freq)

leetcode 236 二叉树的最近公共祖先

递归加回溯有点难

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
        elif left is not None and right is None:
            return left
        elif right is not None and left is None:
            return right
        else:
            return None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值