Monday, April 2, 2018

[2018-Interview] Convert Sorted Array to Binary Search Tree

Original question: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/

My answer: find the root of left and right subtree, and then link them to root. Basically, it is converting each sub-array to a BST


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(nums[(0 + nums.length - 1) / 2]);
        helper(root, nums, 0, (0 + nums.length - 1) / 2 - 1, (0 + nums.length - 1) / 2 + 1, nums.length - 1);
        return root;
    }

    void helper(TreeNode root, int[] nums, int leftMin, int leftMax, int rightMin, int rightMax) {
        TreeNode leftRoot = null;
        TreeNode rightRoot = null;
        if (leftMin <= leftMax) {
            leftRoot = new TreeNode(nums[(leftMin + leftMax) / 2]);   
        }

        if (rightMin <= rightMax) {
            rightRoot = new TreeNode(nums[(rightMin + rightMax) / 2]);
        }
        root.left = leftRoot;
        root.right = rightRoot;
        if (leftRoot != null) {
            helper(leftRoot, nums, leftMin, (leftMin + leftMax) / 2 - 1, (leftMin + leftMax) / 2 + 1, leftMax);    
        }
        if (rightRoot != null) {
            helper(rightRoot, nums, rightMin, (rightMin + rightMax) / 2 - 1, (rightMin + rightMax) / 2 + 1, rightMax);
        }
    }
}

No comments:

Post a Comment