标签:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution 1: recursion
runtime: 28ms.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * 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* sortedListToBST(ListNode* head) { if(!head)return NULL; ListNode *temp=head; int length=0; while(temp){ length++; temp=temp->next; } return sortedListToBST(head, 0, length-1); } TreeNode* sortedListToBST(ListNode *& head, int begin, int end){ if(begin>end)return NULL; int mid=begin+(end-begin)/2; TreeNode *left=sortedListToBST(head,begin,mid-1); TreeNode *root=new TreeNode(head->val); head=head->next; TreeNode *right=sortedListToBST(head,mid+1,end); root->left=left; root->right=right; return root; }
TreeNode* sortedArrayToBST(vector<int>& nums) {
int n=nums.size();
return sortedArrayToBST(nums, 0, n-1);
}
TreeNode* sortedArrayToBST(vector<int>& nums, int start,int end) {
if (start > end) return NULL;
int mid = start + (end - start) / 2;
TreeNode *node = new TreeNode(nums[mid]);
node->left = sortedArrayToBST(nums, start, mid-1);
node->right = sortedArrayToBST(nums, mid+1, end);
return node;
}
};
Solution 2:https://leetcode.com/discuss/29826/clean-c-solution-recursion-o-nlogn-with-comment
标签:
原文地址:http://www.cnblogs.com/irun/p/4759046.html