树的孩子兄弟链表存储结构,采用两条链分别连接孩子和兄弟结点。其中,child指向该结点的第一个孩子结点,sibling指向该结点的下一个兄弟结点。
public class Tree {
private TreeNode root;
private class TreeNode{//树的孩子兄弟链表结点类
T data;
TreeNode child,sibling;//分别指向孩子、兄弟结点
public TreeNode() {
}
public TreeNode(T data){
this(data,null,null);
}
public TreeNode(T data,TreeNode child,TreeNode sibling){
this.data = data;
this.child = child;
this.sibling = sibling;
}
}
public Tree() {
}
public boolean isEmpty(){
return this.root == null;
}
//返回p结点最后一个兄弟结点
public TreeNode getLastSibling(TreeNode p){
if(p==null || p.sibling==null)
return null;
while(p.sibling!=null)
p = p.sibling;
return p;
}
//返回p结点的最后一个孩子
public TreeNode getLastChild(TreeNode p){
if(p==null || p.child==null)
return null;
p = p.child;
while(p.sibling!=null)
p = p.sibling;
return p;
}
//插入x作为根结点
public void insertRoot(T x){
this.root = new TreeNode(x,this.root,null);
}
//插入x作为p结点的最后一个兄弟结点
public TreeNode insertLastSibling(TreeNode p,T x){
if(p==null)
return null;
while(p.sibling!=null)
p = p.sibling;
p.sibling = new TreeNode(x);
return p.sibling;
}
//插入x作为p结点的最后一个孩子结点
public TreeNode insertLastChild(TreeNode p,T x){
if(p==null)
return null;
if(p.child==null){
p.child = new TreeNode(x);
return p.child;
}
else
return insertLastSibling(p.child,x);
}
//先根次序遍历树并返回树的横向凹入表示字符串
public String toString(){
return toString(root,"");
}
//tab表示缩进量
private String toString(TreeNode p,String tab){
if(p==null)
return "";
return tab+p.data.toString()+"\n"+toString(p.child,tab+"\t")+toString(p.sibling,tab);//递归调用
}
public Tree make(){
Tree tree = new Tree();
tree.root = new TreeNode("中国");
tree.insertLastChild(tree.root, "北京市");
tree.insertLastChild(tree.root, "上海市");
TreeNode js = tree.insertLastChild(tree.root, "江苏省");
tree.insertLastChild(js, "南京市");
tree.insertLastChild(js, "苏州市");
TreeNode korea = tree.insertLastSibling(tree.root, "韩国");
tree.insertLastChild(korea,"首尔");
return tree;
}
public static void main(String[] args) {
Tree t = new Tree();
System.out.println(t.make());
}
}