/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head==NULL)//NULL
return NULL;
TreeNode *root=findMid(head,NULL);
return root;
}
TreeNode *findMid(ListNode *start,ListNode *end)
{
if(start==end)
return NULL;
ListNode *slow=start,*fast=start;//find mid node,slow=mid
while(fast!=end&&fast->next!=end)
{
fast=fast->next->next;
slow=slow->next;
}
TreeNode *treeNode =new TreeNode(slow->val);
treeNode->left=findMid(start,slow);
treeNode->right=findMid(slow->next,end);
return treeNode;
}
};
【leetcode】Convert Sorted List to Binary Search Tree
最新推荐文章于 2022-02-19 22:56:38 发布