采用孩子兄弟法构造树和遍历树


/**
* 树用孩子兄弟表示法表示
* @author wanglianqin
*
* 2010-12-9
*/

public class TreeNode {
private TreeNode firstChild;// 孩子
private TreeNode nextsibling;// 兄弟
public Object data;// 数据元素
public int leafNo;

public TreeNode() {
firstChild = null;
nextsibling = null;
}

TreeNode(Object item, TreeNode first, TreeNode next) {
this.data = item;
this.firstChild = first;
this.nextsibling = next;

}

public TreeNode getFirstChild() {
return firstChild;
}

public void setFirstChild(TreeNode firstChild) {
this.firstChild = firstChild;
}

public TreeNode getNextsibling() {
return nextsibling;
}

public void setNextsibling(TreeNode nextsibling) {
this.nextsibling = nextsibling;
}

// 构造树  采用的“层次遍历法”
public TreeNode CreateBiTree() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String value = reader.readLine();
LinkedList<TreeNode> linkedList=new LinkedList<TreeNode>();
//作为指针
TreeNode p=null;
TreeNode q=null;
//保存孩子的字符串数组 至多20个孩子
char[] c=null;
if (value.equals(" ")) {
return null;

} else {
//输入的第一个字符不空
TreeNode root=new TreeNode();
root.data=value;
//入队列
linkedList.add(root);
//当队列不空  建立起子节点
while (linkedList.size()>0) {
p=linkedList.removeFirst();
System.out.println("请输入"+p.data+"的所有孩子");
String str=reader.readLine();
c=str.toCharArray();
if(!str.equals(" "))
{
TreeNode node=new TreeNode();
node.data=c[0];
     p.setFirstChild(node);
     q=node;
     for(int j=1;j<c.length;j++)
     {
    TreeNode next=new TreeNode();
    next.data=c[j];
    q.setNextsibling(next);
    linkedList.add(q);
    q=q.getNextsibling();
     }
q.setNextsibling(null);
linkedList.add(q);
}
}
return root;


}
}

//先序遍历树
public void preOrderTraverse(TreeNode t)
{
if(t!=null)
{
System.out.println(t.data.toString());
preOrderTraverse(t.firstChild);
preOrderTraverse(t.nextsibling);
}
}
}

你可能感兴趣的:(C++,c,C#,J#)