用Java創建二叉樹排序,完成數據的存儲和不同方式的遍歷

package 

public class BinarySortTreeDemo {
    public static void main(String[] args) {
        int[] arr = {7,3,10,12,5,1,9,8,7};
        BinarySortTree binarySortTree = new BinarySortTree();
        //循環添加節點到二叉排序樹
        for (int i = 0; i < arr.length; i++) {
            binarySortTree.add(new Node(arr[i]));
        }
        //中序遍歷二叉排序樹
        System.out.println("中序遍歷二叉排序樹");
        binarySortTree.infixOrder();

    }
}

//創建二叉排序樹
class BinarySortTree{
    private Node root;
    public  void add (Node node){
        if (root == null) {
            root = node;
        }else {
            root.add(node);
        }
    }
    //遍歷二叉樹,其實是由Node類裏的infixOrder完成的。
    public void infixOrder(){
        if (root != null) {
            root.infixOrder();
        }else {
            System.out.println("二叉樹爲空,不能遍歷");
        }
    }
}

class Node {
    int value;
    Node left;
    Node right;

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

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

    public void add(Node node){
        if(node == null){
            return;
        }
        if(node.value < this.value){
            if(this.left == null){
                this.left = node;
            }else {
                this.left.add(node);
            }

        }else {
            if (this.right == null) {
                this.right = node;
            }else {
                this.right.add(node);
            }
        }

    }
    //先序遍歷, 中序遍歷,後序遍歷。  ,先,中,後指的是僞根節點所在(根,左節點,右節點),中的位置
    //不同的遍歷方式,就是調整下面的三個位置
    public void  infixOrder(){
        System.out.println(this +" 0");  //打印爲僞根節點

        if (this.left != null) {        //打印左節點
            this.left.infixOrder();
        }
        
        if (this.right != null) {         //打印右節點
            this.right.infixOrder();
        }
        //System.out.println(this+"1");
    }
}

下面是根據數組裏的數據,在內存中存儲的結構圖,和按先序遍歷的順序,以及代碼運行出來的結果。
在這裏插入圖片描述程序運行出來的結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章