java setroot(),Java中的树实现(root,父级和子级)

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.

5kJXf.gif

解决方案

import java.util.ArrayList;

import java.util.List;

public class Node {

private List> children = new ArrayList>();

private Node parent = null;

private T data = null;

public Node(T data) {

this.data = data;

}

public Node(T data, Node parent) {

this.data = data;

this.parent = parent;

}

public List> getChildren() {

return children;

}

public void setParent(Node parent) {

parent.addChild(this);

this.parent = parent;

}

public void addChild(T data) {

Node child = new Node(data);

child.setParent(this);

this.children.add(child);

}

public void addChild(Node 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;

}

}

Example:

import java.util.List;

Node parentNode = new Node("Parent");

Node childNode1 = new Node("Child 1", parentNode);

Node childNode2 = new Node("Child 2");

childNode2.setParent(parentNode);

Node grandchildNode = new Node("Grandchild of parentNode. Child of childNode1", childNode1);

List> childrenNodes = parentNode.getChildren();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值