Java List to Tree: Convert with Code Example
In Java, we can convert a List into a tree structure by creating tree node objects. Here is an example code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TreeNode {
int val;
List<TreeNode> children;
public TreeNode(int val) {
this.val = val;
this.children = new ArrayList<>();
}
}
public class ListToTree {
public static TreeNode listToTree(List<Integer> list) {
Map<Integer, TreeNode> map = new HashMap<>();
TreeNode root = null;
for (Integer val : list) {
TreeNode node = new TreeNode(val);
map.put(val, node);
}
for (Integer val : list) {
TreeNode node = map.get(val);
if (val == 0) {
root = node;
} else {
TreeNode parent = map.get((val - 1) / 2);
parent.children.add(node);
}
}
return root;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(0);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
TreeNode root = listToTree(list);
}
}
In this code snippet, we first create a TreeNode class to represent tree node objects, with the attributes of node value and a list of child nodes. Next, we iterate through a given List to create tree node objects and store them in a Map, where the key is the node value and the value is the node object. Then, we iterate through the List again to build the tree structure based on the relationships between node values, and return the root node. Finally, by calling the listToTree method, we can convert a List into a tree structure and retrieve the root node.