109. Convert Sorted List to Binary Search Tree

    xiaoxiao2022-06-23  18

    /** * 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) return NULL; ListNode *pre=NULL; ListNode *slow=head; ListNode *fast=head; while(fast->next!=NULL) { fast=fast->next; if(fast->next==NULL) break; fast=fast->next; pre=slow; slow=slow->next; } if(pre)pre->next=NULL; else head=NULL; TreeNode *root=new TreeNode(slow->val); root->left=sortedListToBST(head); root->right=sortedListToBST(slow->next); return root; }
    转载请注明原文地址: https://ju.6miu.com/read-1123384.html

    最新回复(0)