2016-04-14 4 views
0

値の配列が与えられているバイナリ検索ツリーを出力します。バイナリ検索ツリーの原則に従います。図は左に回転しています。
これで所望の出力:

バイナリ検索ツリー配列を出力する

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

あなたは正しく値を挿入していないが、最終的なツリーは、BST(1左側のノードでより多くを持っているではありませんが、3は大きいノードを持っていますその右側にある)。 挿入機能を有効にするには、配列を既にソートしておく必要があります。 値の配列をソートしないままにしたい場合は、挿入中に回転を行う必要があります。詳細はwikipediaまたはrosettaコードを参照してください。 – Guillaume

+0

私のコードを編集しました。私はそれをどのように並べ替えるかについてのアルゴを見つけるでしょう。ありがとう! – Meryel

+0

BSTを使用する際の最も興味深い部分は、ソートされた値ではなく、ランダムな値を挿入する方法を知ることです。あなたの場合、ソートされた配列を使用して値を挿入するのは簡単ですが、実際には値をランダムに挿入するようにしてください。 – Guillaume

答えて

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