My Java Recursive Solution


  • 0
    B

    The method I used is pretty like the Binary Search algorithm.

    Here is my code:

    class Solution {
        
        private TreeNode getNode(int[] nums, int startIndex, int endIndex) {
            if (startIndex > endIndex) {
                return null;
            }
            return new TreeNode(nums[(startIndex + endIndex) / 2]);
        }
        
        private void addNode(TreeNode root, int[] nums, int startIndex, int endIndex) {
            if (root != null) {
                int median = (startIndex + endIndex) / 2;
                
                root.left = getNode(nums, startIndex, median - 1);
                root.right = getNode(nums,  median + 1, endIndex);
                
                addNode(root.left, nums, startIndex, median - 1);
                addNode(root.right, nums, median + 1, endIndex);
            }
        }
        
        public TreeNode sortedArrayToBST(int[] nums) {
            int startIndex = 0;
            int endIndex = nums.length - 1;
    
            TreeNode root = getNode(nums, startIndex, endIndex);
            addNode(root, nums, startIndex, endIndex);        
            
            return root;
        }
    }
    

Log in to reply
 

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