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

/**
* 树用孩子兄弟表示法表示
* @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);
}
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值