二叉搜索树的最小绝对值(力扣

方法一:不推荐,此为本人对二叉搜索树的了解不够到位而写出的代码,适用于所有二叉树

int cmp(const void* a,const void* b)
{
    return *(int*)a-*(int*)b;
}

void dfs(struct TreeNode* root,int* nums,int* pos)
{
    if(!root) return;
    nums[(*pos)++]=root->val;
    dfs(root->left,nums,pos);
    dfs(root->right,nums,pos); 
}

int getMinimumDifference(struct TreeNode* root) {
    int nums[10000],pos=0,min=INT_MAX;
    dfs(root,nums,&pos);
    qsort(nums,pos,sizeof(int),cmp);
    for(int i=1;i

 方法二:适合,此法适合二叉搜索树

void MinDifference(struct TreeNode *Node, int *val, int *Min, int *k)
{
    if (!Node)
        return;
    MinDifference(Node->left, val, Min, k);
    if (*k){
        int t = Node->val - *val;
        if (t < *Min)
            *Min = t;
    }else
        *k = 1;
    *val = Node->val;
    MinDifference(Node->right, val, Min, k);
}

int getMinimumDifference(struct TreeNode* root) {
    int k = 0;
    int val;
    int Min = 0x7fffffff;
    MinDifference(root, &val, &Min, &k);
    return Min;
}

你可能感兴趣的:(深度优先,算法)