Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
原题链接:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
题目:给定一个有正序链表,将其转换成一个二叉搜索树。
思路:能够依照之前的数组的思路来做。即找到中间值。再左右递归建树。
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
int len = 0;
ListNode tmp = head;
while (tmp != null) {
tmp = tmp.next;
len++;
}
return sortedListToBST(head, len);
}
public TreeNode sortedListToBST(ListNode head, int len) {
if (len <= 0)
return null;
int mid = (1 + len) / 2;
ListNode p = head;
int tmp = mid - 1;
while (tmp > 0) {
p = p.next;
tmp--;
}
TreeNode root = new TreeNode(p.val);
root.left = sortedListToBST(head, mid - 1);
root.right = sortedListToBST(p.next, len - mid);
return root;
}
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
// Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}