首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将n进制树中的所有路径按其计数打印出来。

将n进制树中的所有路径按其计数打印出来。
EN

Stack Overflow用户
提问于 2014-11-09 15:15:27
回答 1查看 1.9K关注 0票数 0

我有下面这棵树。节点中的值为窗体名称{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。

代码语言:javascript
运行
复制
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;
}

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-10 09:47:01

代码语言:javascript
运行
复制
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类及其字段:)。祝你今天过得愉快。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26829690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档