代码随想录算法训练营 day 18 | Leetcode 530 501 236

Leetcode 530二叉搜索树的最小绝对值

刚开始觉得最小绝对值一定出现在一个节点与它的左右子节点,后来发现不是专业。二叉搜索树的处理,可以使用中序遍历得到一个有序数组进行处理。

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

Leetcode 501 二叉搜索树的众数

首先,可以先遍历一边二叉树,并使用一个map记录下树中元素出现的次数,再从unordered_map中得到众数。其次,可以利用二叉搜索树的特性,使用中序遍历和双指针来模拟对有序数组的众数求取过程。

class Solution {
public:
    vector<int> result;
    int count = 0;
    int maxCount = 0;
    TreeNode* pre = NULL;
    void searchBT(TreeNode* cur){
        if(cur == NULL) {return;}
        
        searchBT(cur -> left);
        if(pre == NULL){
            count = 1;;
        }else if(pre -> val == cur -> val){
            count++;
        }else if(pre -> val != cur -> val){
            count = 1;
        }

        pre = cur;
        if(count == maxCount){
            result.push_back(cur -> val);
        }

        if(count > maxCount){
            maxCount = count;
            result.clear();
            result.push_back(cur -> val);
        }


        searchBT(cur -> right);
        return;

    }
    vector<int> findMode(TreeNode* root) {
        
        searchBT(root);
        return result;
    }
};

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

有点难,不理解

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

        if (left == NULL && right != NULL) return right;
        else if (left != NULL && right == NULL) return left;
        else  { //  (left == NULL && right == NULL)
            return NULL;
        }

    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值