算法题:树中根节点到到目标节点的路径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);
    }
}
}
相关推荐
萧西待水1 小时前
奥赛一本通 1447 靶形数独
算法·深度优先
星空3 小时前
金蝶苍穹build.gradle配置
java·build.gradle
泯泷3 小时前
那段文字是谁删的?Yjs 14 正式版之前,一套删除归属方案的实现与边界
前端·javascript·算法
hold?fish:palm4 小时前
34 合并K个升序链表
javascript·算法·链表
步行cgn6 小时前
Spring 基于 XML 的自动装配:byName 详解
java·后端·spring
Navigator_Z6 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
大帅点兵6 小时前
Apache Ant 1.9.9 完整讲解
java
LuTshoes6 小时前
spring ai 实战 手搓 PlaneExecuteAgent
java·人工智能·spring·ai
这料鬼有毒6 小时前
二刷hot100-73.矩阵置零
java
caoerzhong7 小时前
JeeWMS 开源仓库管理系统二次开发与接口对接实战:Java WMS 如何与 ERP、MES 和自动化设备打通
java·开源