根据有序链表构造平衡的二叉查找树
leetcode地址:
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/
难度:中等
描述:
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.
Example:
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
解题思路:
分为两步:
1. 把链表转存到一个数组中,问题转化为:将一个有序数组转化为一个平衡二叉查找树。
2. 取数组的中点为根节点,那么根节点的左子树是由左半边的数组生成的,右子树是由数组右半边生成的,分别对数组左半边和右半边进行递归调用
代码:
public class SortedListToBST {
public TreeNode sortedListToBST(ListNode head) {
int size = 0;
ListNode p = head;
while (p != null) {
size++;
p = p.next;
}
ListNode[] listNodes = new ListNode[size];
p = head;
int index = 0;
while (p != null) {
listNodes[index++] = p;
p = p.next;
}
return sortedListToBST(listNodes, 0, listNodes.length);
}
public TreeNode sortedListToBST(ListNode[] listNodes, int start, int end) {
if (start >= end) {
return null;
}
int mid = (end + start) / 2;
TreeNode root = new TreeNode(listNodes[mid].val);
root.left = sortedListToBST(listNodes, start, mid);
root.right = sortedListToBST(listNodes, mid + 1, end);
return root;
}
}