日期:2014-05-20 浏览次数:20865 次
import org.junit.Test;
/**
* 普通树的节点
*
*/
class TreeNode{
/**
* 数据域
*/
private String data;
/**
* 第一个孩子
*/
private TreeNode firstCh;
/**
* 下一个兄弟
*/
private TreeNode nextSib;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public TreeNode getFirstCh() {
return firstCh;
}
public void setFirstCh(TreeNode firstCh) {
this.firstCh = firstCh;
}
public TreeNode getNextSib() {
return nextSib;
}
public void setNextSib(TreeNode nextSib) {
this.nextSib = nextSib;
}
public TreeNode(String data) {
super();
this.data = data;
}
public TreeNode(String data, TreeNode firstCh, TreeNode nextSib) {
super();
this.data = data;
this.firstCh = firstCh;
this.nextSib = nextSib;
}
public TreeNode() {
super();
}
@Override
public String toString() {
return "TreeNode [data=" + data + "]";
}
}
public class Tree {
/**
* 静态数组 用于查表
*/
public static final String[] array={"--","----","------","--------","----------"};
public void outputTree(TreeNode root){
this.preOrder(root, 1);
}
/**
*先序遍历一棵普通树
*1、遍历p自身
*2、递归遍历p的第一个孩子,层数+1
*3、递归遍历p的下一个兄弟,层数不变
*/
public void preOrder(TreeNode node,int ceng){
if(node!=null){
System.out.println(array[ceng-1]+node.getData());
this.preOrder(node.getFirstCh(),ceng+1);
this.preOrder(node.getNextSib(), ceng);
}
}
@Test
public void test(){
TreeNode node1=new TreeNode("三级菜单3");
TreeNode node2=new TreeNode("三级菜单2");
node2.setNextSib(node1);
TreeNode node3=new TreeNode("三级菜单1");
node3.setNextSib(node2);
TreeNode node4=new TreeNode("二级菜单2");
TreeNode node5=new TreeNode("二级菜单1", node3, node4);
TreeNode node6=new TreeNode("一级菜单");
node6.setFirstCh(node5);
this.outputTree(node6);
}
}