簡體   English   中英

輸出二叉搜索樹數組

[英]Outputing Binary Search Tree Array

我想輸出給定值數組的二進制搜索樹。 它遵循二進制搜索樹原理。 該圖向左旋轉。
這是所需的輸出:

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

但是它輸出像這樣
在此處輸入圖片說明

我如何解決它?

//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);
    }
}

具有排序數組的工作代碼:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM