二叉搜索树系列

1. 判断是否为二叉搜索树

public boolean isBinaryTree(TreeNode root, TreeNode min, TreeNode max) {
    if(root == null)
        return true;
    if(min != null && root.val <= min.val) return false;
    if(max != null && root.val >= max.val) return false;
    return isBinaryTree(root.left, min, root) 
        && isBinaryTree(root.right, root, max);
}

class Solution {
    long min = Long.MIN_VALUE;
    public boolean isValidBST(TreeNode root) {
        if(root == null)
            return true;
        if(isValidBST(root.left) && root.val > min) {
            min = root.val;
            return isValidBST(root.right);
        }
        else
            return false;
    }
}

2. 判断一个树是否存在

boolean isInBST(TreeNode root, int target) {
    if(root == null)
        return false;
    if(root.val == target)
        return true;
    if(target < root.val)
        return isInBST(root.left, target);
    if(target > root.val)
        return isInBST(root.right, target);
}

3. 插入节点

  1. root为空,返回一个值为val的新节点
  2. root不为空:
    1. val < root.val:插入到左子树
    2. val > root.val:插入到右子树
TreeNode insert(TreeNode root, int val) {
    if(root == null)
        return new TreeNode(val);
    if(val < root.val)
        root.left = insert(root.left, val);
    if(val > root.val)
        root.right = insert(root.right, val);
    return root;
}

4. 删除元素

  1. 当找到节点时:
    1. 如果左右子树都为null,返回null
    2. 如果一个子树为空,返回不为空的子树
    3. 如果子树都不为空,找到右子树中的最小值,作为根节点的值,然后删除该节点
  2. val小于当前节点值:遍历左子树
  3. val大于当前节点值:遍历右子树
TreeNode delete(TreeNode root, int val) {
    if(root == null)
        return null;
    if(root.val == val) {
        if(root.left == null)
            return right;
      	if(root.right == null)
            return left;
        root.val = getMin(root.right).val;
        root.right = delete(root.right, root.val);
    }
    else if(val < root.val)
        root.left = delete(root.left, val);
    else if(val > root.val)
        root.right = delete(root.right, val);
}

TreeNode getMin(TreeNode root) {
    // BST 最左边的就是最小的
    while(root.left != null)
        root = root.left;
    return root;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值