2016-12-27 97 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); 
    } 
} 

我输入

5 
3 5 4 2 8 

,并返回

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

而不是

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

我试过很多方法来修改代码,让它做什么,我想要,但都失败了...... 如何让我的程序能够检测节点之间的层次结构?我应该做些什么修改?谢谢!

回答

0

你可以改变toString方法Node

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

然后,你可以调用System.out.println(theTree.root)看结构。

+0

非常感谢! –