首页 > 其他 > 详细

Convert Sorted List to Binary Search Tree

时间:2015-03-13 18:36:29      阅读:242      评论:0      收藏:0      [点我收藏+]

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

 

Convert Sorted List to Binary Search Tree

原文:http://www.cnblogs.com/sunshisonghit/p/4335596.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!