算法题:树中根节点到到目标节点的路径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);
    }
}
}
相关推荐
郑州光合科技余经理4 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
To_OC6 小时前
LC 35 搜索插入位置:二分查找谁都会,边界条件谁写谁懵
javascript·算法·leetcode
码哥DFS7 小时前
二叉树的直径
开发语言·javascript·算法
Pluchon8 小时前
Java个人综合项目——萌部落社区V2.0
java·python·spring·spring cloud·postman·idea
梦雨生生9 小时前
java开发工具(学习第一天)
java·开发语言·学习
她说可以呀9 小时前
Spring-ai-alibaba文生图
java·人工智能·spring
营养充电站10 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
人工智能·算法·docker·jupyter
技术小黑10 小时前
RNN算法实战系列05 | 天气预测
人工智能·rnn·算法
松仔log11 小时前
Java中级——组合和继承
android·java·开发语言