[Leetcode] 530. 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
    /
   2

Output:
1

Explanation:
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.

思路

由于是BST,所以只需要中序遍历即可。

代码

/**
 * 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) {
        pre = NULL;
        inOrder(root);
        return ret;
    }
private:
    void inOrder(TreeNode* root) {
        if (root == NULL) {
            return;
        }
        inOrder(root->left);
        if (pre != NULL) {
            ret = min(ret, root->val - pre->val);
        }
        pre = root;
        inOrder(root->right);
    }
    TreeNode *pre = NULL;
    int ret = INT_MAX;
};

你可能感兴趣的:(IT公司面试习题,Leetcode,解题报告,Binary,Search,Tree)