代码随想录算法训练营第21天|530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先

530.二叉搜索树的最小绝对差

方法一:利用中序遍历可以将二叉搜索树转变为一个有序数组,遍历这个数组可以将最小绝对差找到。

方法二:在中序遍历过程中直接利用双指针算出最小绝对差。

class Solution {
public:
    int res = INT32_MAX;
    TreeNode* pre = nullptr;
    void traversal(TreeNode* cur) {
        if (cur == nullptr) return;
        traversal(cur->left);
        if (pre) res = min(res, cur->val - pre->val);
        pre = cur;
        traversal(cur->right);
        return;
    }
    int getMinimumDifference(TreeNode* root) {
        traversal(root);
        return res;
    }
};

501.二叉搜索树中的众数

class Solution {
private:
    vector res;
    int count = 0;
    int maxCount = 0;
    TreeNode* pre = nullptr;
    void traversal(TreeNode* cur) {
        if (cur == nullptr) return;
        traversal(cur->left);
        if (pre == nullptr) {
            count = 1;
        }else if (cur->val == pre->val) {
            count++;
        }else {
            count = 1;
        }
        pre = cur;
        if (count == maxCount) res.push_back(cur->val);
        if (count > maxCount) {
            maxCount = count;
            res.clear();
            res.push_back(cur->val);
        }
        traversal(cur->right);
        return;
    }
public:
    vector findMode(TreeNode* root) {
        traversal(root);
        return res;
    }
};

236. 二叉树的最近公共祖先

从下到上处理一定要用后序遍历。

class Solution {
private:
    TreeNode* traversal(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL) return NULL;
        if (root == p || root == q) return root;
        TreeNode* left = traversal(root->left, p, q);
        TreeNode* right = traversal(root->right, p, q);
        if (left && right) return root;
        else if (left && !right) return left;
        else if (!left && right) return right;
        else return NULL;

    }
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        return traversal(root, p, q);
    }
};

你可能感兴趣的:(算法,c++,数据结构)