写一个列表结构转化为树结构的算法,使用java语言来实现,并且写出工整的代码
时间: 2023-03-12 20:37:51 浏览: 124
Interview-Prep-Code:包括一些我用来准备面试的代码以及一些hackerrank问题
使用 Java 实现列表结构转化为树结构的算法的代码如下:public class ListToTree {
public static TreeNode listToTree(List<Integer> list) {
if (list == null || list.size() == 0) {
return null;
}
// 将list转化成树
TreeNode root = new TreeNode(list.get(0));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int index = 1;
while (index < list.size()) {
TreeNode node = queue.poll();
if (list.get(index) != null) {
TreeNode leftNode = new TreeNode(list.get(index));
node.left = leftNode;
queue.offer(leftNode);
}
index++;
if (index < list.size() && list.get(index) != null) {
TreeNode rightNode = new TreeNode(list.get(index));
node.right = rightNode;
queue.offer(rightNode);
}
index++;
}
return root;
}
}
阅读全文