二叉搜尋樹(Java實現)

來源:互聯網
上載者:User

標籤:microsoft   pop   資料   ext   字母   英文字母   構造   一模一樣   dog   

二叉搜尋樹基本操作
求樹中的結點個數判斷節點是否為空白向樹中插入新結點key-value樹中是否存在key返回樹中key對應的value值先序遍曆中序遍曆後續遍曆層序遍曆求樹中key最小的結點求樹中key最大的結點刪除樹中key最小的結點刪除樹中key最大的結點樹中刪除一個結點
  代碼:
/** * @param <Key> 鍵的泛型 * @param <Value> 值的泛型 */public class BinarySearchTree<Key extends Comparable<? super Key>, Value> {    private class Node {        private Key key; // 鍵,相當於詞典裡的單詞        private Value value; // 值,相當於詞典裡的解釋        private Node left; // 左孩子結點        private Node right;// 右孩子結點        //結點的建構函式        public Node(Key key, Value value) {            this.key = key;            this.value = value;            this.left = null;            this.right = null;        }        // getters  and  setters        public Key getKey() {            return key;        }        public void setKey(Key key) {            this.key = key;        }        public Value getValue() {            return value;        }        public void setValue(Value value) {            this.value = value;        }        public Node getLeft() {            return left;        }        public void setLeft(Node left) {            this.left = left;        }        public Node getRight() {            return right;        }        public void setRight(Node right) {            this.right = right;        }        @Override        public String toString() {            return "Node{" +                    "key=" + key +                    ", value=" + value +                    ‘}‘;        }    }    private Node root; // 二叉搜尋樹的根節點    private int size; //二叉搜尋樹中的結點個數    //樹的建構函式    public BinarySearchTree() {        this.root = null;        this.size = 0;    }    //求樹中的結點個數    public int size() {        return this.size;    }    //判斷節點是否為空白    public boolean isEmpty() {        return this.size == 0;    }    //以node結點為根的樹(子樹)中插入key-value    private Node insert(Node node, Key key, Value value) {        if (node == null) {            size++;            return new Node(key, value);        } else if (node.key.compareTo(key) > 0) {            node.setLeft(insert(node.getLeft(), key, value));        } else if (node.key.compareTo(key) < 0) {            node.setRight(insert(node.getRight(), key, value));        } else { // 相等的時候            node.value = value;        }        return node;    }    //向樹中插入新結點key-value    public void insert(Key key, Value value) {        root = insert(root, key, value);    }    // node結點為根的樹(子樹)中是否存在key    private boolean contain(Node node, Key key) {        if (node == null) {            return false;        } else if (node.key.compareTo(key) == 0) {            return true;        } else if (node.key.compareTo(key) > 0) {            return contain(node.getLeft(), key);        } else {            return contain(node.getRight(), key);        }    }    //樹中是否存在key    public boolean contain(Key key) {        return contain(root, key);    }    //返回node結點為根的樹(子樹)中key對應的value值    private Value search(Node node, Key key) {        if (node == null) {            return null;        } else if (node.getKey().compareTo(key) == 0) {            return node.getValue();        } else if (node.getKey().compareTo(key) > 0) {            return search(node.getLeft(), key);        } else {            return search(node.getRight(), key);        }    }    //返回樹中key對應的value值    public Value search(Key key) {        return search(root, key);    }    //先序遍曆    private void preOrder(Node node) {        if (node == null) return;        System.out.println(node.key);        preOrder(node.getLeft());        preOrder(node.getRight());    }    //先序遍曆    public void preOrder() {        preOrder(root);    }    //中序遍曆    private void inOrder(Node node) {        if (node == null) return;        inOrder(node.getLeft());        System.out.println(node.getKey());        inOrder(node.getRight());    }    //中序遍曆    public void inOrder() {        inOrder(root);    }    //後續遍曆    private void postOrder(Node node) {        if (node == null) return;        postOrder(node.getLeft());        postOrder(node.getRight());        System.out.println(node.getKey());    }    //後續遍曆    public void postOrder() {        postOrder(root);    }    //層序遍曆    public void levelOrder() {        if (root == null) return;        java.util.LinkedList<Node> queue = new java.util.LinkedList<>();        queue.add(root);        while (!queue.isEmpty()) {            Node node = queue.pop();            System.out.println(node);            if (node.getLeft() != null) {                queue.add(node.getLeft());            }            if (node.getRight() != null) {                queue.add(node.getRight());            }        }    }    //以node為根的樹中,key最小的結點    private Node minNode(Node node) {        if (node.getLeft() == null) return node;        return minNode(node.getLeft());    }    //樹中key最小的結點    public Node minNode() {        return minNode(root);    }    //以node為根的樹中,key最大的結點    private Node maxNode(Node node) {        if (node.getRight() == null) return node;        return maxNode(node.getRight());    }    //樹中key最大的結點    public Node maxNode() {        return maxNode(root);    }    //刪除node為根的樹(子樹)中key最小的結點    private Node removeMin(Node node) {        if (node == null) return null;        if (node.getLeft() == null) {            Node rightNode = node.getRight();            node.setRight(null);            size--;            return rightNode;        }        node.setLeft(removeMin(node.getLeft()));        return node;    }    //刪除樹中key最小的結點    public void removeMin() {        root = removeMin(root);    }    //刪除node為根的樹(子樹)中key最大的結點    private Node removeMax(Node node) {        if (node == null) return null;        if (node.getRight() == null) {            Node leftNode = node.getLeft();            node.setLeft(null);            size--;            return leftNode;        }        node.setRight(removeMax(node.getRight()));        return node;    }    //刪除樹中key最大的結點    public void removeMax() {        root = removeMax(root);    }    //刪除一個結點    private Node remove(Node node, Key key) {        if (node == null) return null;        if (key.compareTo(node.key) < 0) {//如果比根小,去左子樹刪除,然後返回根            node.setLeft(remove(node.getLeft(), key));            return node;        } else if (key.compareTo(node.key) > 0) {//如果比根大,去右子樹刪除,然後返回根            node.setRight(remove(node.getRight(), key));            return node;        } else { //key == node.key //如果與當點子樹的根key相等            if (node.getLeft() == null) { //判斷當前子樹的根是否有左子樹                Node rightNode = node.getRight();                node.setRight(null);                size--;                return rightNode;            } else if (node.getRight() == null) {//判斷當前子樹的根是否有右子樹                Node leftNode = node.getLeft();                node.setLeft(null);                size--;                return leftNode;            } else { // 如果當前子樹既有左子樹,又有右子樹                Node successor = minNode(node.getRight());//尋找後繼結點,也就是右子樹中最小的結點                successor = new Node(successor.getKey(), successor.getValue());//建立一個與後繼結點一模一樣的,為了替換                size++;//相當於添加一個結點                successor.setRight(removeMin(node.getRight()));//刪除後繼結點,然後連上原來的右邊                successor.setLeft(node.getLeft());//連上原來的左邊                node.left = node.right = null;//原來的結點已經被替換了,可以不要了。                size--;//相當於刪除一個節點                return successor;//當前新的子樹根就是successor            }        }    }    public void remove(Key key) {        root = remove(root, key);    }    public static void main(String[] args) {        //建立一顆二叉搜尋樹        BinarySearchTree<String, String> bst = new BinarySearchTree<>();        //插入資料        bst.insert("dog", "狗,一種動物");        bst.insert("password", "密碼");        bst.insert("cat", "貓,一種動物");        bst.insert("cup", "杯子");        bst.insert("tom", "湯姆,《貓和老鼠》中的貓");        bst.insert("jerry", "傑瑞,《貓和老鼠》中的老鼠");        bst.insert("a", "26個英文字母中的第一個");        //search()        System.out.println(bst.search("a"));//26個英文字母中的第一個        System.out.println(bst.search("dog"));//狗,一種動物        System.out.println(bst.search("ttttt"));//null        //contain()        System.out.println(bst.contain("cup"));//true        System.out.println(bst.contain("tom"));//true        System.out.println(bst.contain("tttttt"));//false        //maxNode()        System.out.println(bst.maxNode());//Node{key=tom, value=湯姆,《貓和老鼠》中的貓}        //minNode()        System.out.println(bst.minNode());//Node{key=a, value=26個英文字母中的第一個}        //removeMax()        bst.removeMax();        System.out.println(bst.maxNode());//Node{key=password, value=密碼}        //removeMin()        bst.removeMin();        System.out.println(bst.minNode());//Node{key=cat, value=貓,一種動物}        //size()        System.out.println(bst.size());//5        //levelOrder()        bst.levelOrder();        //remove();        System.out.println("--------------");        bst.remove("password");        bst.preOrder();    }}

  

二叉搜尋樹(Java實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.