Any idea on using a helper function that return void?


  • 0
    N
    public class Solution {
    
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(nums[(nums.length - 1) / 2]);
        toBST(nums, 0, nums.length - 1, root);
        return root;
    }
    
    private void toBST(int[] nums, int start, int end, TreeNode root) {
        if (start >= end) {
            return;
        }
        int mid = (start + end) / 2;
        if (mid != start) {
            root.left = new TreeNode(nums[(start + mid - 1) / 2]);
        }
        toBST(nums, start, mid - 1, root.left);
        if (mid != end) {
            root.right = new TreeNode(nums[(mid + 1 + end) / 2]);
        }
        toBST(nums, mid + 1, end, root.right);
    }
    

    }

    I tried to return void in the helper function and pass root as a parameter. I can't get it right without these checks (mid != start, mid != end) before adding it as a child.
    Is there a cleaner one that remove those checks?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.