lintcode 1188 BST的最小绝对差

描述:给定具有非负值的二叉搜索树,找到任意两个节点的值之间的最小[绝对差值]
注意事项
此BST中至少有两个节点。
思路:中根序遍历BST二叉搜索树的值放在vector容器里面,此时容器里的值是升序的,
再依次遍历容器相邻的值取差值,最小的的差值即为所求。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
int ans = INT_MAX;
class Solution {
public:
    /**
     * @param root: the root
     * @return: the minimum absolute difference between values of any two nodes
     */
    int getMinimumDifference(TreeNode * root) {
        // Write your code here
        vector ints;
        calc(root,ints);
        ans = INT_MAX;
        for( int i = 0;i < ints.size() - 1;++i )
        {
            if(ints[i + 1] - ints[i] < ans)
            {
                ans = ints[i + 1] - ints[i];
            }
        }
        return ans;
    }
    void calc(TreeNode *root,std::vector &ints)
    {
        if( !root )
        {
            return;
        }
        calc(root->left,ints);
        ints.push_back(root->val);
        calc(root->right,ints);
    }
};

你可能感兴趣的:(lintcode 1188 BST的最小绝对差)