class TreeNode { int value; List<TreeNode> children; TreeNode(int value) { this.value = value; this.children = new ArrayList<>(); } void addChild(TreeNode child) { children.add(child); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public List<TreeNode> getChildren() { return children; } public void setChildren(List<TreeNode> children) { this.children = children; } }
public class TreeSearch { public static List<TreeNode> treeToList(List<TreeNode> list) { List<TreeNode> result = new ArrayList<>(); for(TreeNode test : list) { List<TreeNode> c = test.getChildren(); result.add(test); if (c!=null) { result.addAll(treeToList(c)); test.setChildren(null); } } return result; } public static TreeNode search(TreeNode root, int target) { if (root == null) { return null; } if (root.value == target) { return root; } for (TreeNode child : root.children) { TreeNode result = search(child, target); if (result != null) { return result; } } return null; } public static void main(String[] args) { // 构建树结构 TreeNode root = new TreeNode(1); root.addChild(new TreeNode(2)); root.addChild(new TreeNode(3)); root.children.get(0).addChild(new TreeNode(21)); root.children.get(0).addChild(new TreeNode(22)); root.children.get(1).addChild(new TreeNode(31)); List<TreeNode> treeNodes = treeToList(root.children); for (TreeNode treeNode : treeNodes) { System.out.println(treeNode.value); } // 查找值为5的节点 // TreeNode result = search(root, 2); // if (result != null) { // System.out.println("找到了节点: " + result.value); // } else { // System.out.println("未找到节点"); // } } }