刷题笔记22——二叉搜索树BST

从叶到花,或从花到叶,于科研是一个过程,而于生命自身则永远只在此刻。花和叶都是一种记忆方式,果子同时也是种子。生命是闪耀的此刻,不是过程,就像芳香不需要道路一样。 ——顾城《一个人应该活得是他自己并且干净》

  • 二叉搜索树:右子树节点值都比node大,左子树节点值都比node小

1038. 从二叉搜索树到更大和树

class Solution {
    int sum = 0;
    public TreeNode bstToGst(TreeNode root) {
        if(root != null){
            bstToGst(root.right);
            sum = sum + root.val;
            root.val = sum;
            bstToGst(root.left);
        }
        return root;
    }
}

538. 把二叉搜索树转换为累加树

class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        sumBST(root);
        return root;
    }

    public void sumBST(TreeNode root){
        if(root==null) return;
        sumBST(root.right);
        sum = sum + root.val;
        root.val = sum;
        sumBST(root.left);
    }
}

AVL 树,红黑树, B+ 树,线段树

230. 二叉搜索树中第K小的元素

class Solution {
    int m = 0;
    int result = -1;
    public int kthSmallest(TreeNode root, int k) {
        findkth(root,k);
        return result;
    }

    public void findkth(TreeNode root,int k){
        if(root==null) return;
        kthSmallest(root.left,k);
        m++;
        if(m==k){
            result = root.val;
        }
        kthSmallest(root.right,k);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值