Leetcode530. Minimum Absolute Difference in BST

来源:互联网 发布:mac dock栏随鼠标跳动 编辑:程序博客网 时间:2024/05/16 06:53

Leetcode530. Minimum Absolute Difference in BST

题目:

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

Example:

Input:   1    \     3    /   2Output:1Explanation:The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

Note: There are at least two nodes in this BST.


题目分析:
首先从题意分析,这是一颗二叉搜索树,当你处于根节点的时候,要和左边最大的比较,和右边最小的比较,同时设一个全局变量min,然后不断左递归和右递归。

代码:
class Solution {private:     int min1 = INT_MAX - 1;public:    int getMinimumDifference(TreeNode* root) {        getMini(root);        return min1;    }    void getMini(TreeNode* root) {        if (!root) return;        int left, right;        if (root->left) {            left = max(root->left);            if (min1 > abs(root->val - left)) min1 = abs(root->val - left);            getMini(root->left);        }        if (root->right) {             right = min(root->right);             if (min1 > abs(root->val - right)) min1 = abs(right - root->val);            getMini(root->right);         }            }    int min(TreeNode* root) {        if (root == NULL) return -1;        if (root->left == NULL) return root->val;        return min(root->left);    }    int max(TreeNode* root) {        if (root == NULL) return -1;        if (root->right == NULL) return root->val;        return max(root->right);    }};



阅读全文
0 0