2017-12-14 4 views
0

AVLツリー挿入のコードを記述しましたが、ルートノードの値を出力しようとすると常にNullが返されます。理由を理解できません。この問題を解決できるのは誰ですか?私は何度も試してみましたが、問題を解決できませんでした。私は混乱しています。私はここに誰かが私が持っている問題を解決するのに役立つことを願っています。私はそこに高いレベルの専門家がいると確信しています。ただ、JavaのAVLツリーデータストラッチャ

public class AVLTreeMethods { 

public Node root = null; 

public int height(Node node){ 
    if (node == null) 
     return 0; 
    return node.height; 
} 

public int max(Node node1, Node node2){ 
    if (node1.height > node2.height) 
     return node1.height; 
    return node2.height; 
} 

public Node rotateRight(Node node){ 
    Node newNode = node.left; 
    node.left = newNode.right; 
    newNode.right = node; 
    node.height = max(node.left,node.right) + 1; 
    newNode.height = max(newNode.left, newNode.right) + 1; 
    return newNode; 
} 


public Node rotateleft(Node node){ 
    Node newNode = node.right; 
    node.right = newNode.left; 
    newNode.left = node; 
    node.height = max(node.left,node.right) + 1; 
    newNode.height = max(newNode.left, newNode.right) + 1; 
    return newNode; 
} 

public Node AVLINSERT(int data, Node root){ 
    if (root == null){ 
     return new Node(data); 
    } 
    else if (data > root.data){ 
     root.left = AVLINSERT(data, root.left); 
    } 
    else if (data < root.data){ 
     root.right = AVLINSERT(data, root.right); 
    } 

    int balance = height(root.left) - height(root.right); 

    if (balance > 1){ 
     if (height(root.left.left) > height(root.left.right)){ 
      return rotateRight(root); 
     } 
     else { 
      root.left = rotateleft(root.left); 
      return rotateRight(root); 
     } 
    } 
    if (balance < -1){ 
     if (height(root.right.right) > height(root.right.left)){ 
      return rotateleft(root); 
     } 
     else 
      root.right = rotateRight(root); 
      return rotateleft(root); 
    } 
    root.height = 1 + max(root.left, root.right); 
    return root; 
} 

public void inorderPrinting(Node root){ 
    inorderPrinting(root.left); 
    System.out.println(root.data); 
    inorderPrinting(root.right); 
} 

public void callingAVLInserting(int data){ 
    AVLINSERT(data,root); 
} 

public void callinInorderPrinting(){ 
    inorderPrinting(root); 
} 

}

答えて

0

あなたのコードを見て、あなたはしかし、あなたがそれを初期化する任意のコンストラクタを持っていないnullにrootを初期化しています。

だから、何かを追加してみてください。

public class AVLTreeMethods { 
    public Node root = null; 

    //add the following 
    public AVLTreeMethods() { 
     //initialize your root appropriately e.g. 
     this.root = new Node(//pass in some data e.g 0) 
    } 
    ...rest of your code 
}