LeetCode: Convert Sorted List to Binary Search Tree


题意:跟上题类似,只不过将向量换成了单链表。
分析:1.解法也是一样的,找到中间值作为根节点,递归。考察点应该在链表的操作上。

2.方法为:先遍历求出链表长度,再遍历到中间节点,并且记录前一个节点,删除中间节点后,将链表切成两段,递归遍历。

 



1
class Solution { 2 public: 3 TreeNode *sortedListToBST(ListNode *head) 4 { 5 TreeNode *root=NULL; 6 if(head) 7 DFSList(root,head); 8 return root; 9 } 10 int getListLength(ListNode *list) 11 { 12 int length=0; 13 ListNode *p=list; 14 while(p!=NULL) 15 { 16 ++length; 17 p=p->next; 18 } 19 return length; 20 } 21 22 23 void DFSList(TreeNode*(&root),ListNode *(&head)) 24 { 25 if(head==NULL) 26 return ; 27 int length=getListLength(head); 28 ListNode *p,*q; 29 p=head; 30 31 p=q=head; 32 int i; 33 for(i=0;i<length/2;++i) 34 { 35 q=p; 36 p=p->next; 37 } 38 root=new TreeNode(p->val); 39 q->next=NULL; 40 if(i==0) 41 return; 42 43 DFSList(root->left,head); 44 DFSList(root->right,p->next); 45 } 46 47 };

 

posted @ 2014-05-29 21:03  dupuleng  阅读(127)  评论(0)    收藏  举报