Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
因为List与Array不一样,因为list只能从前往后遍历,而且不能随机访问,所以无法向Array一样使用前序遍历。因为list只能从前往后遍历,也就是升序遍历,刚好对应二叉搜树的中序遍历。
/**
* 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:
ListNode* now;
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL)
return NULL;
now=head;
int count = 0;
while(now != NULL)
{
now = now->next;
count ++;
}
now = head;
return ListToBST(count);
}
TreeNode* ListToBST(int n)
{
if(n == 0)
return NULL;
TreeNode* root = new TreeNode(0);
root->left = ListToBST(n/2);
root->val = now->val;
now = now->next;
root->right = ListToBST(n-n/2-1);
return root;
}
};