leetcode--ConvertSortedListtoBinarySearchTree

思路:如果用數組可以直接取到中間值,因此可以用前序遍歷的順序來構建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)));
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章