1. 程式人生 > 實用技巧 >二叉排序樹的建立和遍歷

二叉排序樹的建立和遍歷

一個數組建立成對應的二叉排序樹,並使用中序遍歷二叉排序樹,比如:陣列為Array(7,3,10,12,5,1,9),建立成對應的二叉排序樹為

public class BinarySortTreeDemo {
    public static void main(String[] args) {
        int[] arr= {7, 3, 10, 12, 5, 1, 9};
        BinarySortTree binarySortTree = new BinarySortTree();
        for (int i = 0; i < arr.length; i++) {
            binarySortTree.addNode(new Node(arr[i]));
        }
        //遍歷
        binarySortTree.midOrder();
    }
}

class BinarySortTree {
    private Node root;

    //新增節點
    public void addNode(Node node) {
        if (root == null) {
            root = node;
        }else {
            root.addNode(node);
        }
    }

    //中序遍歷節點
    public void midOrder() {
        if (root == null) {
            System.out.println("二叉排序樹為空");
        } else {
            root.midOrder();
        }
    }
}

class Node {

    int val;
    Node left;
    Node right;

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

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

    //新增節點
    public void addNode(Node node) {
        if (this.val > node.val) {
            //需要掛載到左邊
            if (this.left == null) {
                this.left = node;
            } else {
                this.left.addNode(node);
            }
        } else {
            if (this.right == null) {
                this.right = node;
            } else {
                this.right.addNode(node);
            }
        }
    }

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