Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

思想: 利用递归的思想

注意事项:递归是一个输入是一个链表的头指针,同时要链表的尾部节点为null(要保证),否则排序时会导致错乱

java代码:

  1. public TreeNode sortedListToBST(ListNode head) {
  2. TreeNode root=null;
  3. if(head == null) return root;
  4. if(head != null && head.next==null) return new TreeNode(head.val);
  5. if(head!=null && head.next!=null && head.next.next==null) {
  6. TreeNode left = new TreeNode(head.val);
  7. root=new TreeNode(head.next.val);
  8. root.left=left;
  9. return root;
  10. }
  11. ListNode slow = head;
  12. ListNode fast = head;
  13. ListNode pre = slow;
  14. while(fast!=null && fast.next!=null) {
  15. fast = fast.next.next;
  16. pre=slow;
  17. slow = slow.next;
  18. }
  19. fast = slow.next;
  20. slow.next=null; 
  21. root = new TreeNode(slow.val); //slow指向中间节点
  22. pre.next=null;  //第一个链表的节点尾部为null
  23. TreeNode left = sortedListToBST(head);
  24. TreeNode right = sortedListToBST(fast);
  25. root.left=left;
  26. root.right=right;
  27. return root;
  28. }

思想二:

递归:利用每次增加中间节点的方式,并结合节点个数进行递归。

  1. TreeNode* addNode(ListNode * &list,int start,int end) {
  2. if(start>end) return NULL;
  3. int mid=start+(end-start)/2;
  4. TreeNode * left = addNode(list,start,mid-1);
  5. TreeNode *parent=new TreeNode(list->val);
  6. parent->left=left;
  7. list=list->next;  // list指向下一个节点
  8. parent->right=addNode(list,mid+1,end);
  9. return parent;
  10. }
  11. TreeNode *sortedListToBST(ListNode *head) {
  12. if(head==NULL) return NULL;
  13. ListNode *p=head;
  14. int cnt=0;
  15. while(p!=NULL) {
  16. cnt++;
  17. p=p->next;
  18. }
  19. return addNode(head,0,cnt-1);
  20. }
posted @ 2014-07-11 23:19  purejade  阅读(70)  评论(0)    收藏  举报