gpt4 book ai didi

java - 并行化将排序数组转换为二叉搜索树函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:19:58 25 4
gpt4 key购买 nike

我正在尝试用 Java 并行化我的 Convert Sorted Array to BST 程序。因为我的函数以分而治之的方式运行,所以我相信它是可并行的,但一直坚持实现。如果你们能告诉我如何在这里应用线程,那将会非常有帮助。

提前致谢!

// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null) {
return null;
}
return sortedArrayToBST(nums, 0, nums.length - 1);
}

private TreeNode sortedArrayToBST(int[] nums, int start, int end) {
if (start > end) {
return null;
}

int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = sortedArrayToBST(nums, start, mid - 1);
node.right = sortedArrayToBST(nums, mid + 1, end);

return node;
}
}

最佳答案

正如 Andreas 在评论中建议的那样,您可以使用 forkjoinpool 来并行化二叉树创建

 class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

class Task extends RecursiveTask<TreeNode>
{
int[] nums;
int start,end;
public Task(int[] nums,int start,int end)
{
this.nums =nums;
this.start = start;
this.end = end;
}
protected TreeNode compute()
{
if(start>end)
{
return null;
}
int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(nums[mid]);
Task leftSubTask = new Task(nums,start,mid-1);
Task rightSubTask = new Task(nums,mid+1,end);
leftSubTask.fork();
rightSubTask.fork();
node.left = leftSubTask.join();
node.right = rightSubTask.join();
return node;

}
}
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int nums[] = {1,5,7,8,9};
Task task = new Task(nums,0,nums.length-1);
ForkJoinPool forkJoinPool = new ForkJoinPool(4);
TreeNode root = forkJoinPool.invoke(task);
}
}

关于java - 并行化将排序数组转换为二叉搜索树函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38947461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com