2016-12-27 8 views
1

私は正常にバイナリツリーを作ったが、正しくトラバースできない。これは私のバイナリツリープログラムとトラバースメソッドです。バイナリ検索ツリーのトラバースはどのように変更できますか?

import java.util.*; 
public class BinaryTreeUtube { 

    Node root; 
    public void addNode(int key) { 
     Node newNode = new Node(key); 

     if (root == null) { 
      root = newNode; 

     } 
     else { 
      Node focusNode = root; 
      Node parent; 
      while (true) { 
       parent = focusNode; 
       if (key < focusNode.key) { 
        focusNode = focusNode.leftChild; 
        if (focusNode == null) { 
         parent.leftChild = newNode; 
         return; 
        } 
       } else { 
        focusNode = focusNode.rightChild; 
        if (focusNode == null) { 
         parent.rightChild = newNode; 
         return; 
        } 
       } 
      } 
     } 
    } 

    public void inOrderTraverseTree(Node focusNode) { 

     if (focusNode != null) { 


      inOrderTraverseTree(focusNode.leftChild); 
      System.out.print(focusNode + ","); 
      inOrderTraverseTree(focusNode.rightChild); 

     } 


    } 




    public Node findNode(int key) { 

     Node focusNode = root; 

     while(focusNode.key != key) { 
      if (key < focusNode.key) { 
       focusNode = focusNode.leftChild; 
      } 
      else { 
       focusNode = focusNode.rightChild; 
      } 

      if (focusNode == null) { 
       return null; 
      } 
     } 
     return focusNode; 
    } 

    public static void main(String[] args){ 


     BinaryTreeUtube theTree = new BinaryTreeUtube(); 
     Scanner sc = new Scanner(System.in); 
     int times = sc.nextInt(); 
     for (int t = 0; t < times; t++) { 
      theTree.addNode(sc.nextInt()); 
     } 




     theTree.inOrderTraverseTree(theTree.root); 


    } 

} 



class Node { 

    int key; 

    Node leftChild; 
    Node rightChild; 

    Node(int key) { 
     this.key = key; 
    } 

    public String toString() { 
     if (leftChild == null) { 
      return "(-," + Integer.toString(key) + ",-)"; 
     } 
     return Integer.toString(key); 
    } 
} 

I入力

5 
3 5 4 2 8 

、それは私はそれが何を私をやらせるためにコードを変更する方法の多くを試してみました

(-,2,-),3,(-,4,-),5,(-,8,-), 

ではなく

(-,2,-),3,((-,4,-),5,(-,8,-)), 

を返します。欲しいけど、すべて失敗した... 私のプログラムにノード間の階層を検出する機能を与えるにはどうすればよいですか?私は何を変えるべきですか?どうも!

答えて

0

あなたはNodetoString方法に変更することができます:

public String toString() { 
    String l = Objects.toString(leftChild, "-"); 
    String r = Objects.toString(rightChild, "-"); 
    return "(" + l + "," + key + "," + r + ")"; 
} 

次に、あなただけの構造を見るためにSystem.out.println(theTree.root)を呼び出すことができます。

+0

ありがとうございました! –

関連する問題