原题:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:和处理数组的思想类似,用递归。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* 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==NULL) return NULL;
ListNode *tmp = head;
vector<ListNode *> list;
while(!tmp){
list.push_back(tmp);
tmp = tmp->next;
}
return buildBST(list, 0, list.size()-1);
}
TreeNode *buildBST(vector<ListNode *> &list, int left, int right){
if(left>right) return NULL;
int mid = (left+right)/2;
TreeNode *root = new TreeNode(list[mid]->val);
root->left = buildBST(list, left, mid-1);
root->right = buildBST(list, mid+1, right);
return root;
}
};
确实不懂为什么返回值永远是空串。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* 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;
TreeNode *root = NULL;
ListNode *tmp = head;
vector<int> list;
while(!tmp){
list.push_back(tmp->val);
tmp = tmp->next;
}
buildBST(list, root, 0, list.size()-1);
return root;
}
void buildBST(vector<int> &list, TreeNode *&root, int left, int right){
if(left>right) return;
int mid = (left+right)/2;
root = new TreeNode(list[mid]);
buildBST(list, root->left, left, mid-1);
buildBST(list, root->right, mid+1, right);
}
};
while(tmp)....
以后没事还是直接用!=NULL来表示好了……