我有下面这棵树。节点中的值为窗体名称{count}。任何节点的计数值都是包含该节点的路径数。
我需要打印树中的所有路径(从根到叶),直到该节点的计数变为零为止。一旦节点的计数为零,则只打印到其前身的路径(条件是它们的计数大于0)。
上面的图的6条路径是
3-5-1-2-4-6
3-5-1-2
3-5-1-7
3-5-2
3-1-4
3-7
编辑尝试了以下操作。使用运行toString次数的循环调用函数root.count (缩进,节点)。但不知道如何在一条路径(3-5-1-2-4-6)没有孩子之后停下来。而是打印3-5-1-2-4-6-7-2-1-4-7。
public String toString(String indent, MyTree node) {
String output="";
while(node.count>0){
//output = indent + node.toString() + "\n";
output = indent + node.name;
node.count--;
//if(node.count==0) break;
String childsOutput = "";
for (MyTree child : node.childs) {
childsOutput += toString(indent + " ", child);
}
return output + childsOutput;
}
return output;
}
提前谢谢。
发布于 2014-11-10 09:47:01
public void path_Extraction(Node root)
{
int i=0;
while(root.childs.size()!=0)
{
Node childs=root.childs.get(0);
while(childs.count!=0)
{ ArrayList<Node> path=new ArrayList<Node>();
ArrayList<Node> remove=new ArrayList<Node>();
i++;
extract(childs,path,remove);
paths.put(i,path);
Removing_node.remove.put(i, remove);
}
}
}
public void extract(Node childs,ArrayList<Node> path,ArrayList<Node> remove)
{
if(childs.count>1)
{
if(childs.childs.size()>0)
{
extract(childs.childs.get(0),path,remove);
childs.count--;
if(childs.count==0)
{
childs.parent.childs.remove(childs);
childs.parent=null;
path.add(childs);
remove.add(childs);
}
else
{
path.add(childs);
}
}
}
else
{
if(childs.childs.size()>0)
{
extract(childs.childs.get(0),path,remove);
childs.count--;
childs.parent.childs.remove(childs);
childs.parent=null;
path.add(childs);
remove.add(childs);
}
else
{
(childs.count)--;
childs.parent.childs.remove(childs);
childs.parent=null;
path.add(childs);
remove.add(childs);
}
}
}
请注意,这将对您有帮助,因为我做了earlier.Assuming,您有一个Node类及其字段:)。祝你今天过得愉快。
https://stackoverflow.com/questions/26829690
复制相似问题