letcode 分类练习 BST 530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先(自底向上的典型例子)

letcode 分类练习 BST 530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先

BST

重要性质:它的中序遍历是一个有序数组

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


BST的中序遍历是有序数组,所以我们只需要比较有序数组里相邻的元素的差就可以了,这个可以用双指针法,前一个指针是中序的前驱节点

class Solution {
public:
    int diff = INT_MAX;
    TreeNode* pre;
    void dfs(TreeNode* cur){
        if(!cur)return;
        dfs(cur -> left);
        if(pre && abs(pre ->val - cur -> val) < diff){
            diff = abs(pre ->val - cur -> val);
        }
        pre = cur;
        dfs(cur -> right);
        
    }
    int getMinimumDifference(TreeNode* root) {
        dfs(root);
        return diff;
    }
};

501.二叉搜索树中的众数


二叉搜索树的中序遍历是有序数组,所以我们还是可以用上面的方法统计相邻元素是否相等来统计它是不是众数

class Solution {
public:
    vector<int> result;
    int count = 1;
    int maxV = 1;
    TreeNode* pre;
    void dfs(TreeNode* root){
        if(!root) return;
        dfs(root -> left);
        if(pre){W
            if(root -> val == pre -> val)count++;
            else count = 1;
        }
        if(count== maxV && find(result.begin(), result.end(), root->val) == result.end()){
                result.push_back(root->val);
                maxV = count;
        }else if(count > maxV){
                result = vector<int>(1, root->val);
                maxV = count;
        }
        pre = root;
        dfs(root -> right);
    }
    vector<int> findMode(TreeNode* root) {
        if(!root) return result;
        result =  vector<int>(1, root->val);
        dfs(root);
        return result;
    }
};

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


自底向上的典型例题,我们用自底向上的遍历,这个就是后序遍历,然后判断它的左子树和右子树是不是包含p和q,当然p和q会层层向上传递,那么由于自底向上的遍历顺序,第一个遍历到的节点就是最近的公共祖先

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root) return NULL;
        if(root == p) return p;
        if(root == q) return q;
        TreeNode* node_left = lowestCommonAncestor(root -> left, p, q);
        TreeNode* node_right = lowestCommonAncestor(root -> right, p, q);
        if(node_left && node_right)return root;
        else if(node_left) return node_left;
        else if(node_right) return node_right;
        else return NULL;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值