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

十八天打卡,今天的题技巧性比较强,看答案理解过程,需要多做熟练


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

题目链接

做题过程

  • 二叉搜索树的中序遍历是有序数列

迭代法

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

501.二叉搜索树中的众数

题目链接

做题过程

  • 知道用中序遍历可以做,但不知道如何一次遍历就能得到结果

知识点

  • 先处理节点,记录出现的次数
    • 如果pre是空节点,说明cur是首节点,count=1
    • 否则
      • 如果cur的值等于pre的值,count++
      • 如果cur的值不等于pre的值,count=1
    • 更新pre等于cur
  • 再处理次数
    • 如果count等于maxCount,则在结果数组中push当前节点值
    • 如果count大于maxCount,则更新maxCount,清空结果数组,数组中push当前节点值

中序遍历

class Solution {
public:
    vector<int>result;
    int maxCount = 0;
    int count = 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) {
            result.push_back(cur->val);
        } else if (count > maxCount) {
            maxCount = count;
            result.clear();
            result.push_back(cur->val);
        }

        traversal(cur->right);
    }
    
    vector<int> findMode(TreeNode* root) {
        traversal(root);
        return result;
    }
};

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

题目链接

做题过程

  • 没想到思路,这题可用后序遍历做

知识点

  • 在递归函数有返回值的情况下:如果要搜索一条边,递归函数返回值不为空的时候,立刻返回,如果搜索整个树,直接用一个变量left、right接住返回值,这个left、right后序还有逻辑处理的需要,也就是后序遍历中处理中间节点的逻辑(也是回溯)

后序遍历

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == q || root == p || root == nullptr) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left && right) return root;
        else if (left && !right) return left;
        else if (!left && right) return right;
        else return nullptr;
    }
};
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值