一、概述
平衡二叉树是一颗n个节点的高度为lgn的二叉查找树,严格维持节点的左右节点数差的绝对值小于等于1
对于一个已经排好序的链表来说,只需要找到中间点,把其当做root,其左边链表为root的left节点,其右边链表为root的right节点,递归构造就行
二、代码
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
TreeNode *root = NULL;
if (head != NULL) {
ListNode *slow, *fast, *pre;
slow = fast = head;
pre = NULL;
while (fast->next && fast->next->next) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
if (pre != NULL) pre->next = NULL;
else head = NULL;
root = new TreeNode(slow->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
}
return root;
}
};