LeetCode | 0530. 二叉搜索树的最小绝对差【Python】

Problem

LeetCode

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input:

   1
    \
     3
    /
   2

Output:
1

Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

Note:

问题

力扣

给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

示例:

输入:

   1
    \
     3
    /
   2

输出:
1

解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。

提示:

思路

DFS

法一:dfs遍历取节点值,再单独计算最小绝对差
法二:dfs遍历直接进行绝对值比较

Python3 代码

法一

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        # solution one: dfs遍历取节点值,再单独计算最小绝对差
        def dfs(root):
            if not root:
                return
            # 中序遍历是递增的
            if root.left:
                dfs(root.left)
            tmp_val.append(root.val)
            if root.right:
                dfs(root.right)
        tmp_val = []
        dfs(root)
        res = float("inf")
        for i in range(len(tmp_val) - 1):
            res = min(res, abs(tmp_val[i] - tmp_val[i + 1]))
        return res

法二

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        # solution two: dfs遍历直接进行绝对值比较
        pre = -1
        res = float("inf")
        def dfs(root):
            nonlocal pre, res
            if not root:
                return
            # 中序遍历是递增的
            if root.left:
                dfs(root.left)
            if pre != -1:
                res = min(res, abs(pre - root.val))
            pre = root.val
            if root.right:
                dfs(root.right)
        dfs(root)
        return res

GitHub 链接

Python

LeetCode个人题解 文章被收录于专栏

LeetCode个人题解,目前主要是 Python3 题解。

全部评论

相关推荐

1.自我介绍2.介绍一下mcp, skills3.了解react哪些状态管理库4.对话是sse还是什么?是用fetch还是EventSource?5.ts中的any 和 unknown讲一讲6.是直接用组件库的组件还是自己封装了一些别的7.代码输出题1function main() {{var a = 1let b = 2}console.log(a);console.log(b);}main()console.log(a);8.什么是块级作用域 全局作用域 函数作用域9.代码输出题2for (var i = 0;i < 5;i++) {setTimeout(() => {console.log(i);}, 100);}10.代码输出题3for (var i = 0; i < 5; i++){function printText(temp) {setTimeout(() => {console.log(temp);}, 100);}printText(i)}11.代码输出题4for(var i = 0;i < 5;i++){function printText(temp) {var temp = isetTimeout(() => {console.log(temp);}, 100);}printText(i)}12.代码输出题5for(var i = 0;i < 5;i++){function printText(temp) {setTimeout(() => {var temp = iconsole.log(temp);}, 100);}printText(i)}13.点击控制台输出题export default function App() {const [count, setCount] = useState(0)console.log('render',count)return (<div><h1>{count}</h1>{setCount(count + 1)setTimeout(() => console.log('setTimeout', count), 1000)}}>+1</div>)}//这个组件点击按钮后,控制台的输出顺序和值如下:// 1. render 1 (组件重新渲染, count 更新为 1)// 2. setTimeout 0 (1秒后输出,注意这里是 0 而不是 1)14.算法:给有序数组arr = [-4, -1, 0, 3, 5],返回平方后的排序// 有序数组平方后排序const arr = [-4, -1, 0, 3, 5]function solution(arr) {const len = arr.lengthconst result = new Array(len)let left = 0let right = len - 1let index = len - 1while (left <= right) {if (arr[left] * arr[left] > arr[right] * arr[right]) {result[index] = arr[left] * arr[left]left++} else {result[index] = arr[right] * arr[right]right--}index--}return result}console.log(solution(arr));15.反问
查看14道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务