Share My Simple alternative C++ solution


  • 0
    H
    TreeNode *inorder(vector<int>& nums, int root, int &index) {
        if (root > nums.size()) return NULL;
        TreeNode *left = inorder(nums, root * 2, index);
        TreeNode *r = new TreeNode(nums[index++]);
        TreeNode *right = inorder(nums, root * 2 + 1, index);
        r->left = left;
        r->right = right;
        return r;
    }
    
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int index = 1;
        nums.insert(nums.begin(), 0);
        return inorder(nums, 1, index);
    }
    

    The idea is that we can treat the array as trees and construct the tree during in-order traversal. And it guarantee the constructed tree to be the complete binary tree.


Log in to reply
 

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