48ms c++


  • 0
    B
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head)  {
            if (head==NULL) return NULL;
            vector<int> nums;
            ListNode* p = head;
            while (p!=NULL)
            {
                nums.push_back(p->val);
                p=p->next;
            }
            return sortedArrayToBST(nums);
        }
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            if (nums.size()==0) return NULL;
            TreeNode* tmp = new TreeNode(0);
            if (nums.size() == 1)
            {
                tmp->val = nums[0];
                return tmp;
            }
            else
            {
                int mid = nums.size()/2;
                tmp->val = nums[mid];
                vector<int>nleft;
                vector<int>nright;
                nleft.clear();nright.clear();
                for(int i=0;i<mid;i++)
                    nleft.push_back(nums[i]);
                for(int i=mid+1;i<nums.size();i++)
                    nright.push_back(nums[i]);
                tmp->left = sortedArrayToBST(nleft);
                tmp->right = sortedArrayToBST(nright);
            }
            return tmp;
        }
    };
    

Log in to reply
 

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