首页 > 其他分享 >leetcode-530-easy

leetcode-530-easy

时间:2023-01-22 20:12:08浏览次数:39  
标签:easy int 530 getMinimumDifferenceRec minGap lastNum null root leetcode

Minimum Absolute Difference in BST

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.

Example 1:

Input: root = [4,2,6,1,3]
Output: 1
Example 2:

Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:

The number of nodes in the tree is in the range [2, 104].
0 <= Node.val <= 105
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

思路一:利用平衡二叉树有序的特点,使用中序遍历,依次对比

    private static int lastNum = -1;
    private static int minGap = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        lastNum = -1;
        minGap = Integer.MAX_VALUE;
        getMinimumDifferenceRec(root);
        return minGap;
    }

    public void getMinimumDifferenceRec(TreeNode root) {
        if (root == null) {
            return;
        }

        getMinimumDifferenceRec(root.left);
        if (lastNum == -1) {
            lastNum = root.val;
        } else {
            minGap = Math.min(minGap, root.val - lastNum);
            lastNum = root.val;
        }
        getMinimumDifferenceRec(root.right);
    }

标签:easy,int,530,getMinimumDifferenceRec,minGap,lastNum,null,root,leetcode
From: https://www.cnblogs.com/iyiluo/p/17064609.html

相关文章

  • leetcode-405-easy
    ConvertaNumbertoHexadecimalGivenanintegernum,returnastringrepresentingitshexadecimalrepresentation.Fornegativeintegers,two’scomplementmet......
  • leetcode-501-easy
    FindModeinBinarySearchTreeGiventherootofabinarysearchtree(BST)withduplicates,returnallthemode(s)(i.e.,themostfrequentlyoccurredelemen......
  • leetocde-374-easy
    GuessNumberHigherorLowerWeareplayingtheGuessGame.Thegameisasfollows:Ipickanumberfrom1ton.YouhavetoguesswhichnumberIpicked.Eve......
  • LeetCode最长回文子串(/dp)
    原题解题目约束解法解法一#include<iostream>#include<string>#include<vector>usingnamespacestd;classSolution{public:stringlongestPa......
  • LeetCode_单周赛_329
    2544.交替数字和代码1转成字符串,逐个判断classSolution{publicintalternateDigitSum(intn){char[]s=(""+n).toCharArray();intt......
  • 【队列】LeetCode 281. 锯齿迭代器
    题目链接281.锯齿迭代器思路使用队列进行保存代码publicclassZigzagIterator{Queue<Iterator<Integer>>queue=newLinkedList<>();publicZigzagIt......
  • 【队列】LeetCode 346. 数据流中的移动平均值
    题目链接346.数据流中的移动平均值思路队列设计基础题代码classMovingAverage{privateIntegercurrentSum=0;privateQueue<Integer>queue=newLi......
  • [LeetCode] 684. Redundant Connection
    Inthisproblem,atreeisan undirectedgraph thatisconnectedandhasnocycles.Youaregivenagraphthatstartedasatreewith n nodeslabeledfrom......
  • leetcode笔记——328周赛
    1.二维前缀和,二维差分304.二维区域和检索-矩阵不可变-力扣(LeetCode)二维前缀和怎么处理,注意加减的下标 2.2537.统计好子数组的数目-力扣(LeetCode)首先看到子数......
  • 【双指针】LeetCode 409. 最长回文串
    题目链接409.最长回文串思路遍历字符串过程中统计字符出现个数,如果达到2则说明可以放到回文串的两端,需要result+=2。遍历完之后的回文串如果长度小于s,说明s中存......