算法题:树中根节点到到目标节点的路径java

java 复制代码
       import java.util.ArrayList;
import java.util.List;

class Node
{
    public String id;
    public List<Node> children;
    Node()
    {
        id="0";
        children=new ArrayList<>();
    }
}
public class TreePath {
public List<Node>findNodeAndPath2(Node root,String targetId)
{
    List<Node>list=new ArrayList<>();
    if(root==null)return null;
    if(root.id.equals(targetId))
    {
        list.add(root);
        return list;
    }
    list.add(root);
    for(Node n: root.children)
    {
        List<Node>tmp=findNodeAndPath2(n,targetId);
        if(tmp==null) continue;
        if(tmp.get(tmp.size()-1).id.equals(targetId))
        {
            list.addAll(tmp);
            return list;
        }
    }
    return null;

}

测试数据图

java 复制代码
    public static void main(String[] args) {
       Node _13=new Node();
    _13.id="13";
    Node _10=new Node();
    _10.id="10";
    _10.children.add(_13);
    Node _9=new Node();
    _9.id="9";
    Node _4=new Node();
    _4.id="4";
    Node _2=new Node();
    _2.id="2";
    _2.children.add(_4);
    _2.children.add(_9);
    _2.children.add(_10);
    Node _11=new Node();
    _11.id="11";
    Node _19=new Node();
    _19.id="19";
    Node _18=new Node();
    _18.id="18";
    Node _21=new Node();
    _21.id="21";
    Node _20=new Node();
    _20.id="20";
    _18.children.add(_21);
    _18.children.add(_20);
    _11.children.add(_19);
    _11.children.add(_18);
    Node _1=new Node();
    _1.id="1";
    _1.children.add(_2);
    _1.children.add(_11);
    TreePath treePath=new TreePath();
    List<Node>list=treePath.findNodeAndPath2(_1,"20");
    for(Node n:list)
    {
        System.out.println(n.id);
    }
}
}
相关推荐
千纸鹤安安3 小时前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
白鲸开源5 小时前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
白鲸开源5 小时前
一文读懂DolphinScheduler插件机制:如何轻松扩展任务类型与数据源
java·架构·github
七牛开发者5 小时前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
用户298698530149 小时前
Java 实现 Word 文档文本查找与高亮标注
java·后端
宇宙之一粟10 小时前
乐企版式文件生成平台
java·后端·python
plainGeekDev11 小时前
MVC 写法 → MVVM
android·java·kotlin
SL_staff11 小时前
3周搭完MES系统:JVS低代码+JVS-IoT物联网的实战记录
java·前端·低代码