本文主要是介绍leetcode:(109)Conver Sorted List To BST(java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*** 题目:* Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.* For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two* subtrees of every node never differ by more than 1.* 解题思路:* 利用快慢指针找到中间节点,作为根节点,然后左子树即为左边链表部分,右子树即为右边链表部分,递归进行即可。*/ public class SortedListToBST_109_1016 {public TreeNode SortedListToBST(ListNode head) {if (head == null) {return null;}return BST(head, null);}public TreeNode BST(ListNode head, ListNode tail) {if (head == tail) {return null;}//利用快慢指针找到中间节点,作为根节点ListNode slow = head;ListNode fast = head;while (fast != tail && fast.next != tail) {fast = fast.next.next;slow = slow.next;}TreeNode root = new TreeNode(slow.val);root.left = BST(head, slow);root.right = BST(slow.next, tail);return root;}
}
这篇关于leetcode:(109)Conver Sorted List To BST(java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!