二叉排序树的创建和遍历

一个数组创建成对应的二叉排序树,并使用中序遍历二叉排序树,比如:数组为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();
        }
    }
}

原文地址:https://www.cnblogs.com/liuzhidao/p/13887230.html