Convert Sorted List to Binary Search Tree

来源:互联网 发布:赛诺数据官网 编辑:程序博客网 时间:2024/06/17 09:08
/** * 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) {        if(head==NULL) return NULL;//一个结点if(head->next==NULL){TreeNode *ret=new TreeNode(head->val);return ret;}//两个以上结点ListNode *pre=NULL,*slow=head,*fast=head;while(fast->next && fast->next->next){pre=slow;slow=slow->next;fast=fast->next->next;}//slow指向List的中间结点TreeNode *root=new TreeNode(slow->val);if(pre!=NULL) {pre->next=NULL;root->left=sortedListToBST(head);}else{root->left=sortedListToBST(NULL);}root->right=sortedListToBST(slow->next);return root;    }};

0 0