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.

 

思想: 用二分法的思想进行求解,左子树,中间节点,右子树,利用slow和fast指针进行链表分半(其中slow指针所在位置为[N/2]+1;

代码:

public TreeNode sortedListToBST(ListNode head) {

TreeNode root=null;
if(head == null) return root;
if(head != null && head.next==null) return new TreeNode(head.val);
if(head!=null && head.next!=null && head.next.next==null) {
TreeNode left = new TreeNode(head.val);
root=new TreeNode(head.next.val);
root.left=left;
return root;
}
ListNode slow = head;
ListNode fast = head;
ListNode pre = slow;
while(fast!=null && fast.next!=null) {
fast = fast.next.next;
pre=slow;
slow = slow.next;
}
fast = slow.next;
slow.next=null;
root = new TreeNode(slow.val);
pre.next=null;
TreeNode left = sortedListToBST(head);
TreeNode right = sortedListToBST(fast);
root.left=left;
root.right=right;
return root;
}

其中注意处理只有两个节点的情况,slow指针指向尾节点;另外要有pre指针,对前链表的末尾指向null。复杂度为O(nlogn)

改进:

 

TreeNode* addNode(ListNode * &list,int start,int end) {
if(start>end) return NULL;
int mid=start+(end-start)/2;
TreeNode * left = addNode(list,start,mid-1);
TreeNode *parent=new TreeNode(list->val);
parent->left=left;  
list=list->next;  //list pointer to the next node of the left subtree
parent->right=addNode(list,mid+1,end);
return parent;
}
TreeNode *sortedListToBST(ListNode *head) {
if(head==NULL) return NULL;
ListNode *p=head;
int cnt=0;
while(p!=NULL) {
cnt++;
p=p->next;
}
return addNode(head,0,cnt-1);

}

 

 

posted @ 2014-06-23 23:33  purejade  阅读(66)  评论(0编辑  收藏  举报