创建树的代码很简单:
大概说个思路吧:
//节点类
class Node{
public char ch;
public Node parent;
public Node lChild;
public Node rChild;
}
//构建树
//字符串是先序字符串(如:abd,,e,,c,,)
int pos = 0
public Node createTree(String str){
if(str.charAt(pos) == ',') {
return null;
}
Node node = new Node();
node.ch = str.charAt(pos);
pos ++;
Node.lChild = createTree(str);
if(node.lChild != null ) {node.lChild.parent = node;}
pos ++;
Node rChild = createTree(str);
if(node.rChild != null) {node.rChild.parent = node;}
}
//遍历同样递归就很简单了