Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
给定一个按升序排序好的链表,把它转换成一棵平衡的二分查找树。
可以首先把这个链表的长度给求出来,中间的结点就是平衡BST的根结点,它会把链表一分为二,这样就递归地建立左右子树。
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head)
{
int nodeNum = 0;
ListNode *node = head;
while (node)
{
nodeNum++;
node = node->next;
}
return sortedList2BST(head, nodeNum);
}
TreeNode *sortedList2BST(ListNode *head, int nodeNum)
{
if (nodeNum == 0)
return NULL;
int leftnum = nodeNum/2;
int rightnum = nodeNum - leftnum - 1;
ListNode *midnode = head;
for (int i=0; i<leftnum; ++i)
midnode = midnode->next;
TreeNode *root = new TreeNode(midnode->val);
root->left = sortedList2BST(head,leftnum);
root->right = sortedList2BST(midnode->next, rightnum);
}
};
注意在构造树的过程并没有改变原来链表的结构。