class BinaryTree {
 class Node{
 private Comparable data;
 private Node left;
 private Node right;
 public void addNode(Node newNode){
 if(newNode.data.compareTo(this.data)<0){  //要确定是放在左子树还是右子树
 if (left == null){
 left = newNode;                   //放在左子树
 }
 else{
 left.addNode(newNode);
 }
 }
 if(newNode.data.compareTo(this.data)>=0){  
 if (right == null){                    //放在右子树
 right = newNode;
 }
 else{
 right.addNode(newNode);
 }
 }
 }
//---------------------------------------------------------------------- 
 
 public void printNode(){                 //输出采用中序遍历
 if(left!= null){
 left.printNode();
 }
 System.out.print(data+"\t");
 if(right!=null){
 right.printNode();
 }
 }
//---------------------------------------------------------------------- 
 
 }
 private Node root;                   //根元素
 public void add(Comparable data){
 Node newNode = new Node();
 newNode.data = data;
 if(root == null){
 root = newNode;
 }
 else{
 root.addNode(newNode);          //确定节点是放在左子树还是右子树
 }
 } 
 public void print(){            //输出结点
 root.printNode();
 }
 }
 public class DemoTree{
 public static void main(String[] args) {
 BinaryTree bt = new BinaryTree();
 bt.add(8);
 bt.add(3);
 bt.add(10);
 bt.add(9);
 bt.add(1);
 bt.add(5);
 bt.print();
}
 }
各位大侠问下,就是在采用中序遍历这块不明白。就比如上面这串数字,从8开始遍历,因为左子树不空,所以访问到3,左子树还不为空,再访问1,因为1的时候不为空了,所以跳出if循环输出1。到这里我就不明白了,此时右子树为空,所以不会循环里面的。到了这里怎么继续循环呢?(怎么退回到3)

解决方案 »

  1.   

                    8
           3                10
      1       5          9
    print(8) --> print(3);out(8);print(10)
    print(3) --> print(1);out(3);print(5)
    print(1) --> out(1);
    print(5) --> out(5);
    print(10) -->print(9);out(10);
    print(9) --> out(9);简单写个示意..print代表打印节点,out代表System.out.print
    out(1);out(3);out(5);out(8);out(9);out(10)