leetcode-530. Minimum Absolute Difference in BST

考察点:平衡二叉树性质,遍历特点;
思路:BST中序遍历是有序的;
C++ 代码:

/**
 * 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) {
        vector<int> q;
        help(q, root);
        int ret = INT_MAX;
        for (int i=0; i1; i++) {
            if (q[i+1] - q[i] < ret)
                ret = q[i+1] - q[i];
        }
        return ret;
    }
    void help(vector<int>& q, TreeNode * root) {
        if (root->left) {
                help(q, root->left);
        }
        q.push_back(root->val);
        if (root->right) {
            help(q, root->right);
        }
    }
};

你可能感兴趣的:(算法,leetcode,tree)