2016-05-25 9 views
-4

ツリーに1から10000までのランダムな整数を挿入する方法は?私はこれがちょうど挿入のために、あなたはそれがバランスするために別のプロセスが必要であるバイナリツリーを実装してバランスを取る

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

のpublic static無効メイン(文字列[] args)

下のコードで
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

をscanner.inを使用します。

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クラスであると仮定しています
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

私は、お勧めし は、アレイ内のすべての整数を取る配列をソートして、1回のパスでのバイナリツリーを構築し、

あなたの主な方法で

、あなたが持っている必要があります。

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

私はこれをテストしていませんが、私はあなたのコードとの主な問題は、あなたの挿入方法は、トンを取ることだと思いますあなたのコードに1つしか渡していません。 Lemmeはこれが動作するかどうかを知っています。

関連する問題