树的算法题
与树相关的数据题,在此看一到ali的笔试题
附上自己编写的代码
/**
* @author whg
* @date 2021/7/24 7:49 下午
**/
public class Tree {
private List<Node> Node = new ArrayList();
public List<com.ali.node.Node> getNode() {
return Node;
}
public void setNode(List<com.ali.node.Node> node) {
Node = node;
}
}
/**
* @author whg
* @date 2021/7/24 7:48 下午
**/
public class Node {
private String value;
private List<Node> nodes = new ArrayList<>();
public Node(String value) {
this.value = value;
}
public Node(){
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<Node> getNodes() {
return nodes;
}
public void setNodes(List<Node> nodes) {
this.nodes = nodes;
}
}
/**
* 将
* @author whg
* @date 2021/7/24 7:56 下午
**/
public class Data2Tree2Json {
private static Tree tree = new Tree();
public static void toTree(String[] words){
if(words == null){
return;
}
//指向当前层级
List<Node> nodes = tree.getNode();
for (int i = 0; i < words.length; i++) {
Node node = haveSimpleValue(nodes, words[i]);
//没有则加入
if(node == null){
//记录新节点好向下继续遍历
node = add2Nodes(nodes,words[i]);
}
// nodes 转移到下一层
nodes = node.getNodes();
}
}
/**
* 判断是否存在一点的节点
* @param nodes
* @param word
* @return
*/
public static Node haveSimpleValue(List<Node> nodes, String word){
List<Node> collect = nodes.stream()
.filter(node -> node.getValue().equals(word))
.collect(Collectors.toList());
return collect.isEmpty() ? null : collect.get(0);
}
/**
* 将word加入nodes中
* @param nodes
* @param word
*/
public static Node add2Nodes(List<Node> nodes, String word){
if(nodes == null || word == null){
return null;
}
Node node = new Node(word);
nodes.add(node);
return node;
}
public static String tree2Json(){
List<Node> node = tree.getNode();
return "{" + nodes2Json(node) + "}";
}
/**
* 把nodes变成json
* @param nodes
* @return
*/
public static String nodes2Json(List<Node> nodes){
List<String> values = new ArrayList<>();
for (int i = 0; i < nodes.size(); i++) {
Node node = nodes.get(i);
//下一层没有元素则拼接后返回
if(node.getNodes().size() == 0){
String value = "\"" + node.getValue() + "\"" + ":{}";
values.add(value);
}else {
values.add("\"" + node.getValue() + "\"" + ":{" + nodes2Json(node.getNodes()) + "}");
}
}
StringBuilder sb = new StringBuilder();
values.forEach(json ->{
sb.append(json).append(",");
});
return sb.substring(0,sb.length()-1).toString() ;
}
public static void main(String[] args) {
String[] word = new String[]{"中国","浙江","杭州"};
String[] word2 = new String[]{"中国","浙江","杭州","余杭区"};
String[] word4 = new String[]{"中国","浙江","宁波"};
String[] word3 = new String[]{"中国","广东"};
String[] word5 = new String[]{"美国","纽约"};
toTree(word);
toTree(word2);
toTree(word3);
toTree(word4);
toTree(word5);
System.out.println(tree2Json());
}
}