对BST树进行中序遍历,得到递增序列,然后依次计算相邻两元素之间的差,并保存最小的差。

class Solution {
public:
    vector<TreeNode*> V;
    void postTree(TreeNode* node)
    {
        if (node != NULL)
        {
            if (node->left != NULL)
            {
                postTree(node->left);
            }
            V.push_back(node);
            if (node->right != NULL)
            {
                postTree(node->right);
            }
        }
    }
    int minDiffInBST(TreeNode* root) {
        postTree(root);
        int min = INT_MAX;
        if (V.size() < 2)
        {
            return 0;
        }
        int last = V[0]->val;
        for (int i = 1; i < V.size(); i++)
        {
            int diff = V[i]->val - last;
            if (min > diff)
            {
                min = diff;
            }
            last = V[i]->val;
        }
        return min;
    }
};

 

posted on 2018-09-30 16:44  Sempron2800+  阅读(78)  评论(0编辑  收藏  举报