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 a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getLen(ListNode * head)
{
int count = ;
while(head){
head = head->next;
count++;
}
return count;
} TreeNode * createBST(ListNode * head, int beg, int end)
{
if(beg > end)
return NULL;
int mid = beg + (end - beg)/;
ListNode * p = head;
for(int i = beg; i < mid; ++i){
p = p->next;
}
TreeNode * leftNode = createBST(head, beg, mid - );
TreeNode * rightNode = createBST(p->next, mid + , end);
TreeNode * root = new TreeNode(p->val);
root->left = leftNode;
root->right = rightNode;
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
return createBST(head, , getLen(head) - );
}
};
05-11 22:07