并行化转换排序数组到二进制搜索树功能

时间:2016-08-14 23:16:28

标签: java arrays multithreading parallel-processing binary-search-tree

我正在尝试将我的转换排序数组并行化为Java中的BST程序。因为我的函数以Divide and Conquer方式运行,我相信它是可并行化的,但是一直坚持实现。如果你们能告诉我如何在这里应用线程,那将非常有帮助。

提前致谢!

// 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;
    }
}

1 个答案:

答案 0 :(得分:0)

正如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);
    }
}