二叉搜索树的最小绝对差,二叉搜索树中的众数

73 阅读1分钟

二叉搜索树的最小绝对差

[题目](530. 二叉搜索树的最小绝对差)

重点

采用双指针的方式

代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int result = INT_MAX;
    TreeNode* pre = NULL;
public:
    void traversal(TreeNode* cur) {
        if (cur == NULL) {
            return;
        }
        // 左
        traversal(cur->left);
        // 中
        if (pre) {
            result = min(result, cur->val - pre->val);
        }
        pre = cur;
        // 右
        traversal(cur->right);
    }

    int getMinimumDifference(TreeNode* root) {
        traversal(root);
        return result;
    }
};

二叉搜索树中的众数

[题目](501. 二叉搜索树中的众数)

重点

使用双指针,中序遍历

代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    // 最大频率
    int maxCount = 0;
    // 统计频率
    int count = 0;
    TreeNode* pre = NULL;
    vector<int> result;
    void searchBST(TreeNode* cur) {
        if (!cur) {
            return;
        }
        // 左
        searchBST(cur->left);
        // 中
        if (!pre) {
            count = 1;
        }
        // 与前一个节点数值相同
        else if (pre->val == cur->val) {
            count++;
        }
        // 与前一个节点数值不同
        else {
            count = 1;
        }
        pre = cur;
        // 如果和最大值相同,放进result中
        if (count == maxCount) {
            result.push_back(cur->val);
        }
        // 如果计数大于最大值频率
        if (count > maxCount) {
            // 更新频率
            maxCount = count;
            // 关键一步,之前result里的元素都失效了
            result.clear();
            result.push_back(cur->val);
        }
        // 右
        searchBST(cur->right);
    }
public:
    vector<int> findMode(TreeNode* root) {
        count = 0;
        maxCount = 0;
        TreeNode* pre = NULL;
        result.clear();
        searchBST(root);
        return result;
    }
};