資料結構-二叉搜尋樹

酒醉夢醒發表於2021-01-05

資料結構-二叉搜尋樹

結構作用

在這裡插入圖片描述

如上圖所示每個節點都大於左孩子,小於右孩子,以O(logn)複雜度進行如下操作

  • 插入一個元素
  • 查詢是否包含某個元素
  • 刪除某個元素

插入元素7:從根節點出發,7>3,往右邊走,7>5,往右邊走,7>6&&6的右節點為空,把7插入到6的右孩子
在這裡插入圖片描述

刪除節點:如果刪除的節點是根節點,注意修改root,葉子節點找到後直接刪除,例如1,直接把2的左孩子置為null
非葉子節點分為

  • 只含有左孩子的節點例如2,3.left=2.left即可
  • 只含有右孩子的節點例如6,5.right=6.right即可
  • 既有左孩子又有右孩子例如5,此時需要從5的左右子樹選出一個節點頂替5,如果選擇左子樹,需要選擇左子樹中最大的節點,如果選擇右子樹,需要選擇右子樹最小的節點。這裡我們選擇右子樹,那麼使用6來頂替5,6.left=5.left, 3.right=6
    在這裡插入圖片描述

實現

public class BSTTree<E extends Comparable<E>> {

    private class Node{
        public E e;
        public Node left,right;
        public Node(E e){
            this.e = e;
        }
    }

    private Node root;

    private int size;

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size==0;
    }

    //非遞迴
    public boolean addNR(E e){
        if(null==e){
            return false;
        }
        if(null==root){
            root = new Node(e);
            size++;
            return true;
        }
        Node temp = null;
        Node cur = root;
        while(cur!=null){
            temp = cur;
            if(e.compareTo(cur.e)==0){
                return false;
            }else if(e.compareTo(cur.e)<0){
                cur = cur.left;
                if(null==cur){
                    size++;
                    temp.left = new Node(e);
                }
            }else{
                cur = cur.right;
                if(null==cur){
                    size++;
                    temp.right = new Node(e);
                }
            }
        }
        return true;
    }

    public boolean add(E e) {
        if(null==e){
            return false;
        }
        int tempSize = size;
        root = add(root,e);

        return size==tempSize+1;
    }

    private Node add(Node node,E e){
        if(null==node){
            size++;
            return new Node(e);
        }

        if(e.compareTo(node.e)<0){
            node.left = add(node.left,e);
        }else if(e.compareTo(node.e)>0){
            node.right = add(node.right,e);
        }
        return node;
    }

    public boolean containsNR(E e){
        if(null==e){
            return false;
        }
        if(null==root)
            return false;

        Node cur = root;
        while(cur!=null){
            if(e.compareTo(cur.e)==0){
                return true;
            }else if(e.compareTo(cur.e)<0){
                cur = cur.left;
            }else{
                cur = cur.right;
            }
        }
        return false;
    }

    public boolean contains(E e) {
        if(null==e){
            return false;
        }
        return contains(root,e);
    }


    private boolean contains(Node node, E e) {
        if(null==node){
            return false;
        }

        if(e.compareTo(node.e)<0){
            return contains(node.left,e);
        }else if(e.compareTo(node.e)>0){
            return contains(node.right,e);
        }else{
            return true;
        }
    }


    public List<E> preOrder(){
        List<E> list = new ArrayList<>();
        preOrder(root,list);
        return list;
    }

    private void preOrder(Node node,List<E> list){
        if(null==node)
            return;
        list.add(node.e);
        preOrder(node.left,list);
        preOrder(node.right,list);
    }

    public List<E> preOrderNR() {
        List<E> list = new ArrayList<>();
        Stack<Node> stack = new Stack();
        stack.push(root);
        while(!stack.isEmpty()){
            Node cur = stack.pop();
            list.add(cur.e);

            if(cur.right!=null){
                stack.push(cur.right);
            }
            if(cur.left!=null){
                stack.push(cur.left);
            }
        }
        return list;
    }



    public List<E> inOrder(){
        List<E> list = new ArrayList<>();
        inOrder(root,list);
        return list;
    }

    private void inOrder(Node node,List<E> list){
        if(null==node)
            return;
        preOrder(node.left,list);
        list.add(node.e);
        preOrder(node.right,list);
    }

    public List<E> inOrderNR() {
        List<E> list = new ArrayList<>();
        Stack<Node> stack = new Stack();
        Node cur = root;
        while(!stack.isEmpty()||cur!=null){

            while(cur!=null){
                stack.push(cur);
                cur = cur.left;
            }
            //左邊走完了,cur==null
            if(!stack.isEmpty()){
                cur = stack.pop();
                list.add(cur.e);
                cur = cur.right;
            }

        }
        return list;
    }

    public List<E> postOrder(){
        List<E> list = new ArrayList<>();
        postOrder(root,list);
        return list;
    }

    private void postOrder(Node node,List<E> list){
        if(null==node)
            return;
        preOrder(node.left,list);
        preOrder(node.right,list);
        list.add(node.e);
    }

    public List<E> levelOrder(){
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        List<E> list = new ArrayList<>();
        while(!queue.isEmpty()){
             Node cur = queue.poll();
             list.add(cur.e);
              if(cur.left!=null){
                  queue.add(cur.left);
              }
              if(cur.right!=null){
                  queue.add(cur.right);
              }
        }
        return list;
    }

    public E removeMin(){
        E min = min();
        root = removeMin(root);
        return min;
    }

    private Node removeMin(Node node) {
        if(node.left==null){
           Node right = node.right;
           size--;
           node.right = null;
           return right;
        }
        node.left = removeMin(node.left);
        return node;
    }

    public E removeMax(){
        E max = max();
        root = removeMax(root);
        return max;
    }

    private Node removeMax(Node node) {
        if(node.right==null){
            Node left = node.left;
            size--;
            node.left = null;
            return left;
        }
        node.right = removeMax(node.right);
        return node;
    }


    /**
     * 刪除最小值所在節點,返回最小值
     * @return
     */
    public E removeMinNR(){
        E min = min();

        Node cur = root;
        Node par = cur;
        while(cur.left!=null){
            par = cur;
            cur = cur.left;
        }
        //cur是最小值,par是cur的父親
        if(cur==root){
            root=null;
        }else{
            par.left = cur.right;
        }
        size--;
        return min;
    }

    /**
     * 刪除最大值所在節點,返回最大值
     * @return
     */
    public E removeMaxNR(){
        E max = max();

        Node cur = root;
        Node par = cur;
        while(cur.right!=null){
            par = cur;
            cur = cur.right;
        }
        //cur是最小值,par是cur的父親
        if(cur==root){
            root=null;
        }else{
            par.right = cur.left;
        }
        size--;
        return max;
    }

    public Node parentNR(E e){
        if(null==e){
            return null;
        }
        Node cur = root;
        Node par = null;
        while(cur!=null){
            if(e.compareTo(cur.e)<0){
                par = cur;
                cur = cur.left;
            }else if(e.compareTo(cur.e)>0){
                par = cur;
                cur = cur.right;
            }else{
                return par;
            }
        }
        return null;
    }


    public boolean remove(E e) {
        if(null==e)
            return false;
        int tempSize = size;
        root = remove(root,e);
        return size == tempSize-1;
    }

    private Node remove(Node node, E e) {
        if(null==node){
            return null;
        }

        if(e.compareTo(node.e)<0){
             node.left = remove(node.left,e);
             return node;
        }else if(e.compareTo(node.e)>0){
            node.right = remove(node.right,e);
            return node;
        }else{
            //待刪除節點右子樹為空
            if(node.right==null){
               Node left =  node.left;
               size--;
               node.left = null;
               return left;
            }
            //待刪除節點左子樹為空
            if(node.left==null){
                Node right =  node.right;
                size--;
                node.right = null;
                return right;
            }

            // 待刪除節點左右子樹均不為空的情況
            // 找到比待刪除節點大的最小節點, 即待刪除節點右子樹的最小節點
            // 用這個節點頂替待刪除節點的位置

            Node successor = min(node.right);
            successor.left = node.left;
            successor.right = removeMin(node.right);

            node.left = node.right = null;
            return successor;
        }
    }

    public E min(){
        if(size == 0)
            throw new IllegalArgumentException("BST is empty!");
        return min(root).e;
    }

    private Node min(Node node){
        if(node.left==null)
            return node;
        return min(node.left);
    }

    public E max(){
        if(size == 0)
            throw new IllegalArgumentException("BST is empty!");
        return max(root).e;
    }

    private Node max(Node node){
        if(node.right==null)
            return node;
        return max(node.right);
    }


    public List<String> path(){
        List<String> res = new ArrayList<>();
        if(size==0)
            return res;
        path(root,"",res);
        return res;
    }

    private void path(Node node, String s, List<String> res) {
        if(node.left==null&&node.right==null){
            res.add(s+node.e);
        }
        if(node.left!=null){
            path(node.left,s+node.e+"->",res);
        }
        if(node.right!=null){
            path(node.right,s+node.e+"->",res);
        }
    }

    //找到pq最近公共祖先
    public Node lowestCommonAncestor(E p, E q){
        return lowestCommonAncestor(root,p,q);
    }

    public Node lowestCommonAncestor(Node node,E p, E q){
        //pq全在右子樹
        //pq全在左子樹
        //else 找到了
        if(p.compareTo(node.e)>0&&q.compareTo(node.e)>0){
            return lowestCommonAncestor(node.right,p,q);
        }else if(p.compareTo(node.e)<0&&q.compareTo(node.e)<0){
            return lowestCommonAncestor(node.left,p,q);
        }else{
            return node;
        }
    }


    public static void main(String[] args) {
        BSTTree<Integer> tree = new BSTTree<>();
        tree.addNR(2);
        tree.addNR(1);
        tree.addNR(3);
        System.out.println(tree.path());
        tree.removeMax();
        System.out.println(tree.path());

        tree.remove(2);
        System.out.println(tree.path());

        tree.remove(1);
        System.out.println(tree.path());
    }


}

相關文章