解析:这道题本身不难,在二叉排序树的基础上,要求左右子树的深度差小于或等于1,即构建平衡二叉树
分析:设计快慢指针,快指针每次走两步,慢指针每次走一步,根据快慢指针分为两段链表,从head节点至slow节点这段为左子树,slow->next节点至尾结点为右子树,slow指针指向的节点即为根节点,依次重复该过程即可保证左右子树的绝对高度差的绝对值小于或等于1
/**
* 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:
TreeNode* sortedListToBST(ListNode* head) {
if (head == NULL) return NULL;
if (head->next == NULL) return new TreeNode(head->val);
ListNode *pre = head, *slow = head, *fast = head;
while (fast && fast->next){ //寻找划分左子树和右子树的中间节点
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = NULL;
TreeNode* root = new TreeNode(slow->val); //根节点
root->left = sortedListToBST(head); //左子树
root->right = sortedListToBST(slow->next); //右子树
return root;
}
};