2016-05-25 5 views
-4

как сделать вставить случайное целое число от 1 до 10000 в дерево ?? Я только с помощью scanner.in в коде нижереализовать двоичное дерево и сделать его сбалансированным

private BinaryTree insert(BinaryTree node, int value) 
{ 
    if (node == null) 
     node = new BinaryTree(value); 
    else 
    { 
     if (value <= node.getValue()) 
      node.left_child = insert(node.left_child, value); 
     else 
      node.right_child = insert(node.right_child, value); 
    } 
    return node; 
} 

государственной статической силы основных (String [] арг)

do  
    { 
     //tree operations 
     System.out.println("\nTree Operations\n"); 
     System.out.println("1. insert "); 


     int choice = scan.nextInt();    
     switch (choice) 
     { 
     case 1 : 
      System.out.println("get integer element to insert"); 
      bst.insert(scan.nextInt());      
      break;          
     default : 
      System.out.println("Wrong Entry \n "); 
      break; 
     } 
+3

В чем проблема? Вы получаете сообщение об ошибке? Неправильный результат? – Mureinik

+1

Я думаю, вам нужно переосмыслить, как вы внедряете свой BT –

ответ

-2

Это только для вставки, вам нужен другой процесс, чтобы сделать его сбалансированным. Я хотел бы предложить, принять все целые числа в массиве, Отсортировать массив, а затем построить бинарное дерево, в один проход,

private BinaryTree constructBalanced(int a[], int low, int high) { 

    if (low > high) return null; 
    else { 

    int mid = (low + high)/2; 
    BinaryTree root = new BinaryTree(a[mid]); 
    root.left = constructBalanced(int a[], low, mid - 1); 
    root.right = constructBalanced(int a[], int mid + 1, high); 
    return root; 
    } 
} 
+0

ой, я пропустил это. –

0

Я предполагаю, что ваш BinaryTree класс выглядит следующим образом:

public BinaryTree{ 

private int value = null; 
private BinaryTree left_child=null; 
private BinaryTree right_child=null; 
//Also insert getters and setters here 

BinaryTree(value){ 
this.value = value; 
} 

private BinaryTree insert(BinaryTree node, int value) 
{ 
    if (node == null) 
     node = new BinaryTree(value); 
    else 
    { 
     if (value <= node.getValue()) 
      node.left_child = insert(node.left_child, value); 
     else 
      node.right_child = insert(node.right_child, value); 
    } 
    return node; 
} 
} 

В вашем основном методе, вы должны иметь:

BinaryTree node = new BinaryTree("RootValue"); 
do{ 
    //tree operations 
    System.out.println("\nTree Operations\n"); 
    System.out.println("1. insert "); 


    int choice = scan.nextInt();    
    switch (choice) 
    { 
    case 1 : 
     System.out.println("get integer element to insert"); 
     node = bst.insert(node,scan.nextInt());      
     break;          
    default : 
     System.out.println("Wrong Entry \n "); 
     break; 
    } 

Я не проверял, но я думаю, что основная проблема с вашим кодом является то, что ваш метод вставки занимает т wo, но вы передаете только один код. Лемм знает, работает ли это.