2016-04-14 138 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); 
    } 
}