二叉搜索树实现

重新再看一遍自己写的这玩意简直群魔乱舞
二叉搜索树简而言之就是,左树所有结点都小,右树所有结点都大。
知道了这一点就能写了,尤其是不用考虑平衡的时候还是很好写的。
Java实现如下

首先是实现树结点的内部类

    private class Node{
        Node left;
        Node right;
        int val;
        Node(){left=right=null;val=0;}
        Node(int v){left=right=null;val=v;}
        Node(Node l,Node r,int v){left=l;right=r;val=v;}
    }

插入
按照二叉搜索树的规则进行迭代,查找插入的位置。
特别注意出次插入的时候,也就是向空二叉树中插入的情况

    public void add(int n){
        if(isEmpty()){
            root = new Node(n);
        }else{
            Node cnt = find(n);
            if(cnt.val==n){
                return;
            }else{
                if(cnt.val>n){
                    cnt.left = new Node(n);
                }else{
                    cnt.right = new Node(n);
                }
            }
        }
    }

查找
同插入,基本差不多

    public Node find(int n){
        Node cnt = root;
        Node last = root;
        while(last.val!=n && cnt!=null){
            last=cnt;
            if(last.val>n){
                cnt = last.left;
            }else{
                cnt=last.right;
            }
        }
        return last;
    }

删除
这应该是最难写的了 也是群魔乱舞的祸源
这里可以有更加优美的写法,但是当时考虑不周,只想到了交换结点,而没有考虑利用函数返回值,每次都返回一棵符合要求的二叉树

    public void erase(int n){
        if(isEmpty()){
            throw new EmptyStackException();
        }
        Node pos = root;
        Node fPos = null;
        while(pos!=null && pos.val!=n){
            fPos=pos;
            if(pos.val>n){
                pos=pos.left;
            }else{
                pos=pos.right;
            }
        }
        if(pos==null){
            throw new NoSuchElementException();
        }
        Node eraseNodeLeft = pos.left;
        Node eraseNodeRight = pos.right;
        Node replace=null,lastReplace=null;
        if(pos.left!=null){
            replace = pos.left;
            while(replace.right!=null) {
                lastReplace=replace;
                replace = replace.right;
            }
            if(lastReplace!=null) {
                lastReplace.right = replace.left;
                replace.left = eraseNodeLeft;
            }
            replace.right=eraseNodeRight;
        }else {
            if (pos.right != null) {
                replace = pos.right;
                while (replace.left != null) {
                    lastReplace = replace;
                    replace = replace.left;
                }
                if (lastReplace != null) {
                    lastReplace.left = replace.right;
                    replace.right = eraseNodeRight;
                }
                replace.left = eraseNodeLeft;
            }
        }

        if(fPos!=null){
            int val = replace==null? n:replace.val;
            if(fPos.val>val)
                fPos.left=replace;
            else
                fPos.right=replace;
        }else{
            root = replace;
        }
    }

留个坑,填一个更加优美的删除方式

测试文件代码

import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Random;

/*
 * フブキすきすき大好き❣
 */

public class forTest {
    public static void main(String[] args) {
        SearchBinaryTree t = new SearchBinaryTree();
        Random r =new Random();
        ArrayList<Integer> store = new ArrayList<>();
        int len = 10;
        for (int i = 0; i < len; i++) {
            int tmp = r.nextInt(50);
            t.add(tmp);store.add(tmp);
        }
        System.out.println(store);
        System.out.println("\n");
        t.show();
        System.out.println("\n");
        for (int i = 0; i < len; i++) {
            try {
                System.out.println("erase "+store.get(i));
                t.erase(store.get(i));
                t.show();
                System.out.println("\n");
            }catch (NoSuchElementException e){
                System.out.println(e);
                System.out.println(store.get(i)+" may duplicated\n");
            }
        }
    }
}

二叉树类完整文件

package com.java.myCollection;

import java.util.EmptyStackException;
import java.util.NoSuchElementException;

public class SearchBinaryTree {
    private class Node{
        Node left;
        Node right;
        int val;
        Node(){left=right=null;val=0;}
        Node(int v){left=right=null;val=v;}
        Node(Node l,Node r,int v){left=l;right=r;val=v;}
    }
    private static final Node EMPTY_TREE =null;
    private Node root;
    SearchBinaryTree(){root = EMPTY_TREE;}
    public boolean isEmpty(){
        return root==EMPTY_TREE;
    }
    public void add(int n){
        if(isEmpty()){
            root = new Node(n);
        }else{
            Node cnt = find(n);
            if(cnt.val==n){
                return;
            }else{
                if(cnt.val>n){
                    cnt.left = new Node(n);
                }else{
                    cnt.right = new Node(n);
                }
            }
        }
    }
    public Node find(int n){
        Node cnt = root;
        Node last = root;
        while(last.val!=n && cnt!=null){
            last=cnt;
            if(last.val>n){
                cnt = last.left;
            }else{
                cnt=last.right;
            }
        }
        return last;
    }
    public void erase(int n){
        if(isEmpty()){
            throw new EmptyStackException();
        }
        Node pos = root;
        Node fPos = null;
        while(pos!=null && pos.val!=n){
            fPos=pos;
            if(pos.val>n){
                pos=pos.left;
            }else{
                pos=pos.right;
            }
        }
        if(pos==null){
            throw new NoSuchElementException();
        }
        Node eraseNodeLeft = pos.left;
        Node eraseNodeRight = pos.right;
        Node replace=null,lastReplace=null;
        if(pos.left!=null){
            replace = pos.left;
            while(replace.right!=null) {
                lastReplace=replace;
                replace = replace.right;
            }
            if(lastReplace!=null) {
                lastReplace.right = replace.left;
                replace.left = eraseNodeLeft;
            }
            replace.right=eraseNodeRight;
        }else {
            if (pos.right != null) {
                replace = pos.right;
                while (replace.left != null) {
                    lastReplace = replace;
                    replace = replace.left;
                }
                if (lastReplace != null) {
                    lastReplace.left = replace.right;
                    replace.right = eraseNodeRight;
                }
                replace.left = eraseNodeLeft;
            }
        }

        if(fPos!=null){
            int val = replace==null? n:replace.val;
            if(fPos.val>val)
                fPos.left=replace;
            else
                fPos.right=replace;
        }else{
            root = replace;
        }
    }
    public void show(){
        if(root==null){
            System.out.println("Is Empty!");
            return;
        }
        show(root);
    }
    private void show(Node now){
        StringBuffer txt = new StringBuffer("left:"+String.valueOf(now.val)+" - ") ;
        if(now.left!=null){
            txt.append(now.left.val);
            show(now.left);
        }else{
            txt.append("null");
        }
        txt.append("    ").append("right:"+now.val+" - ");
        if(now.right!=null){
            txt.append(now.right.val);
            show(now.right);
        }else{
            txt.append("null");
        }
        System.out.println(txt.toString());
    }
}

以下是Java实现二叉搜索树的基本步骤和代码示例: 1.定义二叉搜索树节点类 ```java class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } ``` 2.定义二叉搜索树类 ```java class BST { private TreeNode root; public BST() { root = null; } // 向二叉搜索树中插入元素 public void insert(int val) { root = insert(root, val); } private TreeNode insert(TreeNode node, int val) { if (node == null) { return new TreeNode(val); } if (val < node.val) { node.left = insert(node.left, val); } else if (val > node.val) { node.right = insert(node.right, val); } return node; } // 在二叉搜索树中查找元素 public boolean search(int val) { return search(root, val); } private boolean search(TreeNode node, int val) { if (node == null) { return false; } if (val == node.val) { return true; } else if (val < node.val) { return search(node.left, val); } else { return search(node.right, val); } } // 删除二叉搜索树中的元素 public void delete(int val) { root = delete(root, val); } private TreeNode delete(TreeNode node, int val) { if (node == null) { return null; } if (val < node.val) { node.left = delete(node.left, val); } else if (val > node.val) { node.right = delete(node.right, val); } else { if (node.left == null) { return node.right; } else if (node.right == null) { return node.left; } TreeNode minNode = findMin(node.right); node.val = minNode.val; node.right = delete(node.right, node.val); } return node; } private TreeNode findMin(TreeNode node) { while (node.left != null) { node = node.left; } return node; } } ``` 3.测试代码 ```java public class TestBST { public static void main(String[] args) { BST bst = new BST(); bst.insert(5); bst.insert(3); bst.insert(7); bst.insert(1); bst.insert(9); System.out.println(bst.search(3)); // 输出:true bst.delete(3); System.out.println(bst.search(3)); // 输出:false } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值