Convert Sorted List to Binary Search Tree

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.

思路:

  典型的dfs思路

我的代码:

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null)    return null;
        if(head.next == null) return new TreeNode(head.val);
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode mid = getMiddle(head, dummy);
        TreeNode root = new TreeNode(mid.val);
        TreeNode left = sortedListToBST(dummy.next);
        TreeNode right = sortedListToBST(mid.next);
        root.left = left;
        root.right = right;
        return root;
    }
    public ListNode getMiddle(ListNode head, ListNode dummy)
    {
        ListNode pre = dummy;
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != null && fast.next != null)
        {
            slow = slow.next;
            fast = fast.next.next;
            pre = pre.next;
        }
        pre.next = null;
        return slow;
    }
}
View Code

 

posted on 2015-03-13 17:11  zhouzhou0615  阅读(114)  评论(0编辑  收藏  举报

导航