LeetCode 530. Minimum Absolute Difference in BST

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);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41256413/article/details/81480908