[ 数据结构 ] 二叉排序树(BST)

0 引出

需求:给定数列 (7, 3, 10, 12, 5, 1, 9),要求能够高效的完成对数据的查询和添加

方案:

  1. 数组未排序:如果不对数组排序,添加元素只需扩容并放到最后,速度快,但是查找慢
  2. 数组排序:有序数组使用查找算法,找起来是快,但是每次添加元素需要查找并整体移动数据,即添加慢
  3. 链表:不管链表是否有序,查找速度都慢,添加数据速度比数组快,不需要数据整体移动。
  4. 二叉排序树,BST: (Binary Sort(Search) Tree),将数列值作为权值创建节点,构建二叉排序树

1 二叉排序树的创建

  1. 所谓创建二叉树,其实就是从一颗没有节点的空树开始,不断添加节点,树从无到有根节点,到最后一个节点的添加,最终完成树的创建,因此我们需要编写添加节点的方法,实现自动创建树,而非手动改变每个节点的指向
  2. 保证添加每一个节点都满足二叉排序树的硬要求:左子节点的值比当前节点的值小,右子节点的值比当前节点的值大
  3. add方法内容:不断比较待添加节点和当前节点的权值,比当前节点小则判断是否有左子节点,没有则可以作为左子节点添加了,有左子节点则对左子节点递归调用add方法,对于待添加节点权值比当前节点的权值大的情况,和前面的处理同理
//添加节点
    public void add(Nd nd) {
        if (nd == null) {
            return;
        }
        if (nd.value < this.value) {
            if (this.left == null) {
                this.left = nd;
            } else {
                this.left.add(nd);
            }
        } else {
            if (this.right == null) {
                this.right = nd;
            } else {
                this.right.add(nd);
            }
        }
    }

2 二叉排序树的删除

  1. 相比创建时的简单添加节点,删除操作就需要考虑很多了,毕竟需要考虑放置删除节点的左右子树
  2. 先不谈删除root节点的特殊情况,删除节点的类型分为三种:叶子节点、有单子树、有双子树
  3. 删叶子节点:比如2,找到2和父节点1,看2是1的左子节点还是右子节点,然后将1的右指针置空,完成删除
  4. 删有单子树节点:比如1,找到1和父节点3,1是3的左子节点,2是1的右子节点,直接更新3的左子节点为2,完成删除
  5. 删有单子树节点:比如10,找到10和父节点7,两种删法:要么将10改为10的左子树中最大值9然后删除原来的9节点(叶子节点),要么将10改为10的右子树中最小值11然后删除原来的11节点(叶子节点),完成删除
  6. 对于root节点的删除,只需模仿上面345加以判断即可

image-20230108220034338.png

//二叉排序树
public class App04_BinarySortTree {
    public static void main(String[] args) {
        int[] arr = {7, 3, 10, 12, 5, 1, 9,2,11};
        BinarySortTree tree = new BinarySortTree();
        for (int i : arr) {
            tree.add(new Nd(i));
        }
        tree.infixOrder();
        System.out.println("-------删除前------");

        tree.delNode(11);
        tree.delNode(2);
        tree.delNode(9);
        tree.delNode(5);
        tree.delNode(1);
        tree.delNode(12);
        tree.delNode(3);
        tree.delNode(10);
        tree.delNode(7);
        tree.infixOrder();

    }
}

class BinarySortTree {
    private Nd root;

    public Nd getRoot() {
        return root;
    }

    //中序遍历
    public void infixOrder() {
        if (root != null) {
            root.infixOrder();
        } else {
            System.out.println("树为空!!!");
        }
    }

    //添加节点
    public void add(Nd nd) {
        if (root == null) {
            root = nd;
        } else {
            root.add(nd);
        }
    }

    //找到删除节点及其父节点
    public Nd search(int value) {
        if (root == null) {
            return null;
        } else {
            return root.search(value);
        }
    }
    public Nd searchParent(int value) {
        if (root == null) {
            return null;
        } else {
            if (root.getLeft() == null && root.getRight() == null) {
                return null;
            } else {
                return root.searchParent(value);
            }
        }
    }

    //删除节点
    public void delNode(int value) {
        if (root == null) {
            return;
        } else {
            Nd target = search(value);
            Nd parent = searchParent(value);//为空则只能是删根节点
            //有的删才行
            if (target != null) {
                if (parent != null) {
                    //删叶子节点
                    if (target.getLeft() == null && target.getRight() == null) {
                        if (parent.getLeft()!=null&&parent.getLeft().getValue() == value) {
                            parent.setLeft(null);
                        } else {
                            parent.setRight(null);
                        }

                    //删有双子树的节点
                    } else if (target.getLeft() != null && target.getRight() != null) {
                        //target为左子树
                        if (parent.getLeft().getValue() == value) {
                            int max = delLeftTreeMax(target);
                            target.setValue(max);
                        //target为右子树
                        } else {
                            int min = delRightTreeMin(target);
                            target.setValue(min);
                        }

                    //删有单子树的节点
                    } else {
                        //4种可能,左左,左右,右左,右右
                        if (parent.getLeft()!=null&& parent.getLeft().getValue() == value && target.getLeft() != null) {
                            parent.setLeft(target.getLeft());
                        } else if (parent.getLeft() != null && parent.getLeft().getValue() == value && target.getRight() != null) {
                            parent.setLeft(target.getRight());
                        } else if (parent.getRight().getValue() == value && target.getLeft() != null) {
                            parent.setRight(target.getLeft());
                        } else {
                            parent.setRight(target.getRight());
                        }
                    }
                } else {//没有父节点,说明就是删root,因为删除的节点存在
                    //叶子
                    if (root.getLeft() == null && root.getRight() == null) {
                        root = null;
                    //有双子树
                    } else if (root.getLeft() != null && root.getRight() != null) {
                        //用左子树最大或右子树最小都可以
                        root.setValue(delLeftTreeMax(root.getLeft()));

                    //有单子树
                    } else {
                        if (root.getRight() != null) {
                            root = root.getRight();
                        } else {
                            root = root.getLeft();
                        }
                    }
                }
            } else {
                System.out.println("删除的节点不存在!!!");
            }
        }
    }

    //删左子树,最大值
    public int delLeftTreeMax(Nd nd) {
        Nd temp = nd;
        while (true) {
            if (temp.getRight() == null) {
                break;
            }
            temp = temp.getRight();
        }
        delNode(temp.getValue());
        return temp.getValue();
    }
    //删右子树,最小值
    public int delRightTreeMin(Nd nd) {
        Nd temp = nd;
        while (true) {
            if (temp.getLeft() == null) {
                break;
            }
            temp = temp.getLeft();
        }
        delNode(temp.getValue());
        return temp.getValue();
    }
}
class Nd {
    private int value;
    private Nd left;
    private Nd right;

    public Nd(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Nd getLeft() {
        return left;
    }

    public void setLeft(Nd left) {
        this.left = left;
    }

    public Nd getRight() {
        return right;
    }

    public void setRight(Nd right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "Nd [value=" + value + "]";
    }

    //中序遍历
    public void infixOrder() {
        if (this.left != null) {
            this.left.infixOrder();
        }
        System.out.println(this);
        if (this.right != null) {
            this.right.infixOrder();
        }
    }

    //添加节点
    public void add(Nd nd) {
        if (nd == null) {
            return;
        }
        if (nd.value < this.value) {
            if (this.left == null) {
                this.left = nd;
            } else {
                this.left.add(nd);
            }
        } else {
            if (this.right == null) {
                this.right = nd;
            } else {
                this.right.add(nd);
            }
        }
    }

    //查找要删除节点
    public Nd search(int value) {
        if (this.value == value) {
            return this;
        } else if (value < this.value) {//这里对于==的处理与add方法保持一致
            if (this.left != null) {
                return this.left.search(value);
            }
        } else {
            if (this.right != null) {
                return this.right.search(value);
            }
        }
        return null;
    }
    //查找要删除的节点的父节点
    public Nd searchParent(int value) {
        if ((this.left != null && this.left.value == value) ||
                this.right != null && this.right.value == value) {
            return this;
        } else {
            if (value < this.value && this.left != null) {
                return this.left.searchParent(value);
            } else if (value >= this.value && this.right != null) {
                return this.right.searchParent(value);
            } else {
                return null;
            }
        }
    }
}

3 总结

  1. 对于二叉排序树,中序遍历结果就是原数列升序排序后的结果
  2. 为什么说二叉排序树结合数组+链表的优点? 它的查找速度其实等价于有序数组的二分查找速度,而它的添加速度基于二分查找在找到位置后等于链表的链尾追加操作(改变空指针的指向),因此得名
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉排序树,也称为二叉搜索树(Binary Search Tree,简称BST),是一种特殊的二叉树结构,它具有以下性质: 1. 对于二叉排序树的任意一个非叶子节点,其左子树的所有节点的值都小于该节点的值,右子树的所有节点的值都大于该节点的值。 2. 对于二叉排序树的任意一个节点,其左子树和右子树都是二叉排序树。 下面是一个示例代码,演示了如何构建一个二叉排序树,并进行插入和查找操作: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def insert(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return root def search(root, val): if root is None or root.val == val: return root if val < root.val: return search(root.left, val) else: return search(root.right, val) # 构建二叉排序树 root = None values = [5, 3, 8, 2, 4, 7, 9] for val in values: root = insert(root, val) # 查找节点 target = 4 result = search(root, target) if result: print("找到了节点", target) else: print("未找到节点", target) ``` 这段代码首先定义了一个`TreeNode`类,表示二叉排序树的节点。然后定义了`insert`函数,用于向二叉排序树中插入节点。最后定义了`search`函数,用于在二叉排序树中查找指定的节点。通过构建二叉排序树并进行查找操作,可以实现对数据的快速插入和查找。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值