代码随想录训练营day18|二叉树part6

二叉搜索树的最小绝对差

力扣题目链接

class Solution {
public:
    int result = INT_MAX;
    int pre;
    int getMinimumDifference(TreeNode* root) {
        //初始化,避免未更新的pre与第一个值做差得到0
        if(root->left)
            pre = root->val;
        else
            pre =root->right->val;
        inorder(root);
        return result;
    }
    void inorder(TreeNode* root){
        if(!root)
            return;
        if(root->left){
            inorder(root->left);
        }
        result = min(abs(root->val - pre), result);
        pre = root->val;
        if(root->right){
            inorder(root->right);
        }
    }
};

二叉搜索树中的众数

力扣题目链接

class Solution {
public:
    int counts = 0;
    int maxcounts = 0;
    int pre;
    vector<int> result;
    vector<int> findMode(TreeNode* root) {
        pre = root->val;
        inorder(root);
        return result;
    }
    void inorder(TreeNode* root){
        if(root->left)  inorder(root->left);
        if(root->val == pre){
            counts++;
            if(maxcounts < counts){
                maxcounts = counts;
                result.clear();
                result.push_back(root->val);
            }
            else if(maxcounts == counts){
                result.push_back(root->val);
            }
        }
        // 重新计数
        else{
            pre = root->val;
            counts = 1;
            // 避免全是1次出现
            if(maxcounts < counts){
                maxcounts = counts;
                result.clear();
                result.push_back(root->val);
            }
            else if(maxcounts == counts){
                result.push_back(root->val);
            }
        }
        if(root->right) inorder(root->right);
    }
};

pre用Treenode进行初始化时可以减少很多讨论

二叉树的最近公共祖先

力扣题目链接

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == p || root == q || !root)
            return root;
        if(root->left && !root->right)
            return lowestCommonAncestor(root->left, p, q);
        if(root->right && !root->left)
            return lowestCommonAncestor(root->right, p, q);
        TreeNode* r = lowestCommonAncestor(root->right, p, q);
        TreeNode* l = lowestCommonAncestor(root->left, p, q);
        if(r && l)
            return root;
        if(!r && l)
            return l;
        if(!l && r)
            return r;
        return nullptr;//没有找到p||q
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值