LeetCode Convert Sorted List to Binary Search Tree

// 168ms
1
/** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 /** 10 * Definition for binary tree 11 * struct TreeNode { 12 * int val; 13 * TreeNode *left; 14 * TreeNode *right; 15 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 * }; 17 */ 18 class Solution { 19 public: 20 TreeNode *sortedListToBST(ListNode *head,int len) { 21 int mid=len/2,tem; 22 tem=mid; 23 TreeNode *root,*left,*right; 24 ListNode *p,*q,*r; 25 p=head; 26 27 q=NULL; 28 while(tem) 29 { 30 tem--; 31 q=p; 32 p=p->next; 33 } 34 root=new TreeNode(p->val); 35 36 if(mid) 37 root->left=sortedListToBST(head,mid); 38 if(len-mid-1) 39 root->right=sortedListToBST(p->next,len-mid-1); 40 return root; 41 } 42 TreeNode *sortedListToBST(ListNode *head) { 43 // Start typing your C/C++ solution below 44 // DO NOT write int main() function 45 ListNode *p=head; 46 if(head==NULL) 47 return NULL; 48 49 int count=0; 50 while(p) 51 { 52 count++; 53 p=p->next; 54 } 55 return sortedListToBST(head,count); 56 } 57 };
原文地址:https://www.cnblogs.com/mengqingzhong/p/3118290.html