Convert Sorted List to Binary Search Tree

来源:互联网 发布:淘宝修改宝贝详情影响 编辑:程序博客网 时间:2024/05/01 12:41

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

思路:这题应该与 Convert Sorted Array to Binary Search Tree 联系起来考虑,这样思路就很清晰了。

准确的说,都是root应该是中点,左子树比root小,右子树比root大,首先应该找root,然后用recursion循环去build左右子树。

注意:fast != end && fast.next != end.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } *//** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode sortedListToBST(ListNode head) {        if(head == null) return null;        return build(head, null);    }        public TreeNode build(ListNode start, ListNode end){        if(start == end){            return null;        }                ListNode slow = start;        ListNode fast = start;                while(fast!= end && fast.next!=end){            slow = slow.next;            fast = fast.next.next;        }                TreeNode node = new TreeNode(slow.val);        node.left = build(start,slow);        node.right = build(slow.next, end);        return node;    }}


0 0
原创粉丝点击