Traditional use recursion to find out all the top parent, recycling call getChild (), recursive calls getChild () in getChild () in.
This way I do not feel very good understanding of the complexity of detail for the n + n (the number of all children nodes) , the first n number of executions for detecting all parent node, n (the number of the parent node + all children the number of nodes) is determined from the set each time whether there is a child node. If a set is complete tree structure, the number of the parent node number + all children nodes = n, i.e., to calculate the number of n ^ 2 + n, big O notation O (^ n-2) .
I do so, double loop for matching child nodes, another filter out all child nodes collection. code show as below:
@Data
public class CommentTreeRespDto implements Serializable {
private static final long serialVersionUID = 9098462797193334657L;
@ApiModelProperty(value = "评论父id,顶级父id为00000-00000-00000-00000")
private String parentId;
@ApiModelProperty(value = "当前日志评论的id")
private String id;
@ApiModelProperty(value = "评论内容")
private String content;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
@ApiModelProperty(value = "评论人")
private String createdBy;
@ApiModelProperty(value = "当前评论下的子评论")
private List<CommentTreeRespDto> childCommentList;
}
复制代码
public List<CommentTreeRespDto> getComment(IdBean<String> id) {
List<CommentTreeRespDto> comment = queryDao.executeForObjectList("selDiaComByDiaId", id);
comment.forEach(c -> {
comment.forEach(m -> {
if (c.getId().equals(m.getParentId())) {
if (!CollectionUtils.isEmpty(m.getChildCommentList())) {
c.getChildCommentList().add(m);
} else {
List<CommentTreeRespDto> cs = Lists.newArrayList();
cs.add(m);
c.setChildCommentList(cs);
}
}
});
});
return comment.stream()
.filter(e->(!e.getParentId().equals(PARENT_ID)))
.collect(Collectors.toList());
}
复制代码
In this way I
- Easy to understand, than the recursive loop characteristic for a double point of it better understood, using the set.
- Code is simple, with Java8 Stream flow + lambda expressions, Introduction to understand.
- In the complete tree structure, the same time complexity. Double loop for filtering n ^ 2 + child node n.
Comments are welcome to write what you think. Together we exchange ~
Every growth, want to share with you. (Whispered BB, with a number of public lottery.)