题目描述
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路: https://siddontang.gitbooks.io/leetcode-solution/content/tree/convert_sorted_listarray_to_binary_search_tree.html
//对于二叉树来说,左子树小于根节点,而右子树大于根结点。所以需要找到链表的中间节点,这个就是根节点。
//链表的左半部分就是左子树,而右半部分是右子树,继续递归处理相应的左右部分,就可以构造对应的二叉树了。
//难点在于如何找到链表的中间节点,可以通过fast、slow指针来解决,fast走两步,slow每次走一步,fast走到尾,slow就是中间节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedListToBST(ListNode *head) { return build(head,NULL); } TreeNode *build(ListNode *start,ListNode *end) { if(start==end) { return NULL; } ListNode *fast=start; ListNode *slow=start; while(fast!=end &&fast->next!=end) { fast=fast->next->next; slow=slow->next; } TreeNode *node=new TreeNode(slow->val); node->left=build(start,slow); node->right=build(slow->next,end); return node; } };