输出二进制搜索树阵列

时间:2016-04-14 14:08:45

标签: java binary-search-tree

我想在给定值数组的情况下输出二叉搜索树。它遵循二进制搜索树原则。图表向左旋转 这是所需的输出:

                  <6 
            <5
      4<
3<          
            <2
      1<

但它输出像这样 enter image description here

我该如何解决?

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

    Node(int x) {
        value = x;
    }
}

//class BST
public class BST {
    static int value[] = {3,4,5,6,1,2};
    public static Node root;

    public static Node insert(int num[], int start, int end) {
        if (start > end)
            return null;

        int mid = (start + end) / 2;
        Node roots = new Node(value[mid]);
        roots.left = insert(value, start, mid - 1);
        roots.right = insert(value, mid + 1, end);

        display(roots, 0);
        return roots;
    }

    public static void display(Node node, int level){
        if(node!=null){
            display(node.right, level+1);
            System.out.println("");
            if(node==root)
                System.out.print("Root-> ");
            for(int i=0;i<level&&node!=root;i++)
                System.out.print("             ");
            System.out.print(node.value+"< ");
            display(node.left, level+1);
        }
    }

    public static void main(String args[]){
        insert(value, 0, 5);
    }
}

1 个答案:

答案 0 :(得分:0)

带有排序数组的工作代码:

public class BST {
    static int value[] = {1,2,3,4,5,6};
    public static Node root;

    public static Node insert(int[] num) {
        if (num.length == 0)
                return null;

        return insert(num, 0, num.length - 1);
    }

    public static Node insert(int num[], int start, int end) {
        if (start > end)
            return null;

        int mid = (start + end) / 2;
        Node roots = new Node(value[mid]);
        roots.left = insert(value, start, mid - 1);
        roots.right = insert(value, mid + 1, end);

        return roots;
    }

    public static void display(Node node, int level){
        if(node!=null){
            display(node.right, level+1);
            System.out.println("");
            if(node==root)
                System.out.print("Root-> ");
            for(int i=0;i<level&&node!=root;i++)
                System.out.print("             ");
            System.out.print(node.value+"< ");
            display(node.left, level+1);
        }
    }

    public static void main(String args[]){
        display(insert(value), 0);
    }
}