欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 530. Minimum Absolute Difference in BST

程序员文章站 2022-03-07 18:12:42
...

530.Minimum Absolute Difference in BST

LeetCode 530. Minimum Absolute Difference in BST



解析

该面壁的代码。晚上二刷。
https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/

class Solution {
public:
    int q(int x){
        return x>0?x:-x;
    }
    int getMinimumDifference(TreeNode* root) {
        int* path = new int[10000];
        int len=0;
        travel(root,path,len);
        int min = path[1]-path[0];
        for(int i=1;i<len;i++){
            int diff = path[i]-path[i-1];
            min = min>diff ? diff:min;
        }
        return min;
    }
    void travel(TreeNode* root,int* path,int& len){
        if(root == NULL)
            return;
        travel(root->left,path,len);
        path[len++] =root->val;
        travel(root->right,path,len);
    }
};