随想录二刷Day21——二叉树

二叉树

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

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

思路:
记录二叉树的遍历结果,对结果排序,取相邻差值最小的结果。

class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        vector<int> path;
        preorder(root, path);
        sort(path.begin(), path.end());
        int minn = 100005;
        int path_size = path.size();
        for (int i = 1; i < path_size; i++) {
            minn = minn < (path[i] - path[i - 1]) ? minn : (path[i] - path[i - 1]);
        }
        return minn;
    }

private:
    void preorder(TreeNode *root, vector<int> &path) {
        if (root == nullptr) return ;
        path.push_back(root->val);
        preorder(root->left, path);
        preorder(root->right, path);
    }
};

25. 二叉搜索树中的众数

501. 二叉搜索树中的众数

思路:
中序遍历二叉搜索树,得到一个单调不减序列,遍历过程中记录众数的最大数目:

  1. 当某个数值的数目等于最大数目时,将其加入结果集。
  2. 当某个数值的数目大于最大数目时,将之间的结果集清空,加入最新的结果。
class Solution {
public:
    vector<int> findMode(TreeNode* root) {
        vector<int> ans;
        cnt = 1;
        midordered(root, ans);
        return ans;
    }

private:
    int cnt = 1, max_cnt = 1, pre = 100005;
    void midordered(TreeNode *root, vector<int> &ans) {
        if (root == nullptr) return ;
        midordered(root->left, ans);
        if (root->val == pre) {
            cnt++;
            if (max_cnt < cnt) {
                max_cnt = cnt;
                while (ans.size() > 0) {
                    ans.pop_back();
                }
            }
        } else {
            cnt = 1;
            pre = root->val;
        }
        if (max_cnt == cnt) ans.push_back(root->val);
        midordered(root->right, ans);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值