题目描述链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/
解题思路:递归,分治。给出的链表为有序升序链表,找出中位数作为根节点,中位数之前的为左子树,之后为右子树。
如此递归在建立左子树和右子树即可。
LeetCode C++ 参考代码如下:
/** * 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) { return buildTree(head,NULL); } ListNode* getMid(ListNode* left,ListNode* right){ ListNode *slow=left; ListNode *fast=left; while(fast!=right&&fast->next!=right){ slow=slow->next; fast=fast->next; fast=fast->next; } return slow; } TreeNode* buildTree(ListNode* left,ListNode* right){ if(left==right){ return NULL; } ListNode* mid=getMid(left,right); TreeNode* root=new TreeNode(mid->val); root->left=buildTree(left,mid); root->right=buildTree(mid->next,right); return root; } };