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

530. Minimum Absolute Difference in BST

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

Problem

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

Example

530. Minimum Absolute Difference in BST

Solution

BST中差值绝对值最小,只能出现在相邻节点。
本题与501题是类似的。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
            int ret = INT_MAX;
            TreeNode* pre = NULL;

            inOrder(root,pre,ret);

            return ret;
        
        

    }

    void inOrder(TreeNode* root,TreeNode* &pre,int &ret)
    {
        if(!root)
            return;
        inOrder(root->left,pre,ret);

        if(pre)
        {
            int curAD = abs(root->val - pre->val);
            if(curAD < ret)
            {
                ret = curAD;
            }
        }

        pre = root;

        inOrder(root->right,pre,ret);

    }
};