Java 中的树实现(根、父级和子级)

编程入门 行业动态 更新时间:2024-10-28 11:22:37
本文介绍了Java 中的树实现(根、父级和子级)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要创建一个类似于 Java 中附加图像的树结构.我发现了一些与此相关的问题,但没有找到令人信服且解释清楚的答复.应用业务包括食品超级品类(主菜、甜点等).这些类别中的每一个都可以有父项或子项等.

I need to create a tree structure similar as the attached image in Java. I've found some questions related to this one but I haven't found a convincing and well explained response. The application business consists in food super categories (main courses, desserts and other). Each of these categories can have parent items or children items and so on.

推荐答案

import java.util.ArrayList; import java.util.List; public class Node<T> { private List<Node<T>> children = new ArrayList<Node<T>>(); private Node<T> parent = null; private T data = null; public Node(T data) { this.data = data; } public Node(T data, Node<T> parent) { this.data = data; this.parent = parent; } public List<Node<T>> getChildren() { return children; } public void setParent(Node<T> parent) { parent.addChild(this); this.parent = parent; } public void addChild(T data) { Node<T> child = new Node<T>(data); child.setParent(this); this.children.add(child); } public void addChild(Node<T> child) { child.setParent(this); this.children.add(child); } public T getData() { return this.data; } public void setData(T data) { this.data = data; } public boolean isRoot() { return (this.parent == null); } public boolean isLeaf() { return this.children.size == 0; } public void removeParent() { this.parent = null; } }

示例:

import java.util.List; Node<String> parentNode = new Node<String>("Parent"); Node<String> childNode1 = new Node<String>("Child 1", parentNode); Node<String> childNode2 = new Node<String>("Child 2"); childNode2.setParent(parentNode); Node<String> grandchildNode = new Node<String>("Grandchild of parentNode. Child of childNode1", childNode1); List<Node<String>> childrenNodes = parentNode.getChildren();

更多推荐

Java 中的树实现(根、父级和子级)

本文发布于:2023-10-26 12:46:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!