二叉查找树

1 11 搜索区间

    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<>();
        help(root, k1, k2, res);
        return res;
    }
    public void help(TreeNode root, int k1, int k2, ArrayList<Integer> res){
        if (root == null) return;
        if (k1 < root.val){
            help(root.left, k1, k2, res);
        }
        if (k1 <= root.val && root.val <= k2){
            res.add(root.val);
        }
        if (root.val < k2){
            help(root.right, k1, k2, res);
        }
    }
View Code

2 85 插入节点

    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if (root == null){
            return node;
        }
        if (root.val > node.val) {
            root.left = insertNode(root.left, node);
        } else {
            root.right = insertNode(root.right, node);
        }
        return root;
    }
View Code

3 661 Conver BST to Greater Tree

public class Solution {
    /**
     * @param root the root of binary tree
     * @return the new root
     */
     int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        // Write your code here
        help(root);
        return root;
    }
    public TreeNode help(TreeNode root){
        if (root == 0) return;
        if (root.right != null){
            help(root.right);
        }
        sum += root.val;
        root.val = sum;
        if (root.left != null){
            help(root.left);
        }
    }
}
View Code

4 95 验证二叉查找树

    public boolean isValidBST(TreeNode root) 
    {
        return help(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    public boolean help(TreeNode root, long min, long max);
    {
        if (root == null) return true;
        if (root.val <= min || root.val >= max) return false;
        return help(root.left, min, Math.min(root.val, max)) &&
               help(root.right, Math.max(root.val, min));
    }
View Code

 

转载于:https://www.cnblogs.com/whesuanfa/p/7017421.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值