select middle element as root in every recursion


  • 0
    N
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            //insert from middle
            return recursion(nums, 0, nums.size() - 1);
        }
        
        TreeNode* recursion(vector<int>& nums, int i, int j) {
            if (i > j)
                return NULL;
            int mid = i + (j - i) / 2;
            TreeNode* root = new TreeNode(nums[mid]);
            root->left = recursion(nums, i, mid - 1);
            root->right = recursion(nums, mid + 1, j);
            
            return root;
        }
    };
    

Log in to reply
 

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