算法训练营笔记day21|530. 二叉搜索树的最小绝对差、501. 二叉搜索树中的众数、236. 二叉树的最近公共祖先

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

题目连接

笔记

中序遍历用数组vec记录val,遍历数组vec找到最小绝对差

class Solution {
public:
    void traversal(TreeNode* node, vector<int>& vec) {
        if (NULL == node) return;
        traversal(node->left, vec);
        vec.push_back(node->val);
        traversal(node->right, vec);
    }
    int getMinimumDifference(TreeNode* root) {
        vector<int> vec;
        traversal(root, vec);
        int result = INT_MAX;
        for (int i = 0; i < vec.size() - 1; i++) {
            if (abs(vec[i] - vec[i + 1]) < result) result = abs(vec[i] - vec[i + 1]);
        }
        return result;
    }
};

501. 二叉搜索树中的众数

题目连接

笔记

用一个pre记录前一个节点,记录重复的个数count,与maxCount比较,留下最大的count

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

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

题目连接

笔记

返回时要返回记录的节点

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

你可能感兴趣的:(算法,leetcode,职场和发展)