packageBTree;/***@author* 链表实现二叉树
* 三种遍历方式:先根遍历,中根遍历,后根遍历*/
public classLinkOfBTree {
Node root= null;//初始化二叉树
public LinkOfBTree(intdata){
root= newNode(data);
}//新增节点
public void add(intdata){
Node node= newNode(data);
Node temp=root;while(true){if(temp.data >=data){if(temp.leftChild != null)
temp=temp.leftChild;else{
temp.leftChild=node;break;
}
}else{if(temp.rightChild != null)
temp=temp.rightChild;else{
temp.rightChild=node;break;
}
}
}
}/**打印二叉树:递归
*node:初始数据为根节点*
*先根遍历*/
public voiddisplayRootFirst(Node node){
System.out.println("节点值:"+node.data);if(node.leftChild != null)
displayRootFirst(node.leftChild);if(node.rightChild != null)
displayRootFirst(node.rightChild);
}/*** 中根遍历二叉树*/
public voiddisplayRootMid(Node node){if(node.leftChild != null)
displayRootMid(node.leftChild);
System.out.println("节点值:"+node.data);if(node.rightChild != null)
displayRootMid(node.rightChild);
}/*** 后根遍历二叉树*/
public voiddisplayRootLast(Node node){if(node.leftChild != null)
displayRootLast(node.leftChild);if(node.rightChild != null)
displayRootLast(node.rightChild);
System.out.println("节点值:"+node.data);
}public static voidmain(String[] a){
LinkOfBTree tree= new LinkOfBTree(10);
tree.add(8);
tree.add(7);
tree.add(3);
tree.add(11);
tree.add(3);
tree.add(20);
tree.add(26);
tree.add(11);
System.out.println("------先根遍历------");
tree.displayRootFirst(tree.root);
System.out.println("------中根遍历------");
tree.displayRootMid(tree.root);
System.out.println("------后根遍历------");
tree.displayRootLast(tree.root);
}
}