您的位置:首页 > 其它

leetcode--ConvertSortedListtoBinarySearchTree

2015-06-23 10:14 393 查看
思路:如果用数组可以直接取到中间值,因此可以用前序遍历的顺序来构建BST。但是链表如果要取中间值需要n/2的时间,因此采用中序遍历的顺序来构建BST。 这样root生成的顺序就和中序遍历的顺序一样,也就是list从前往后的顺序。

import java.util.List;

/**
* Created by marsares on 15/6/23.
*/
public class ConvertSortedListtoBinarySearchTree {
ListNode ln;
public TreeNode sortedListToBST(ListNode head) {
ln=head;
return traversal(1,getLen(head));
}
public TreeNode traversal(int start,int end){
if(start>end)return null;
int mid=(start+end)/2;
TreeNode left=traversal(start,mid-1);
TreeNode root=new TreeNode(ln.val);
ln=ln.next;
TreeNode right=traversal(mid+1,end);
root.left=left;
root.right=right;
return root;
}
public int getLen(ListNode head){
if(head==null)return 0;
int len=1;
while(head.next!=null){
len++;
head=head.next;
}
return len;
}
public static void main(String[]args){
ConvertSortedListtoBinarySearchTree csltobst=new ConvertSortedListtoBinarySearchTree();
BinaryTreeSerialize bts=new BinaryTreeSerialize();
ListNode n0=new ListNode(1);
ListNode n1=new ListNode(2);
ListNode n2=new ListNode(3);
ListNode n3=new ListNode(4);
ListNode n4=new ListNode(5);
n0.next=n1;
n1.next=n2;
n2.next=n3;
n3.next=n4;
System.out.println(bts.Serialize(csltobst.sortedListToBST(n0)));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode BST 中序遍历