109.有序链表转换二叉搜索树
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
解析代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private ListNode findMiddleElement(ListNode head) {
//定义三个指针
ListNode prev_ptr = null;
ListNode slow_ptr = head;
ListNode fast_ptr = head;
//利用双指针进行迭代,遍历整个链表,并找到中间节点
//条件:快指针不能指向空,且其下一个节点也不能为空开始循环迭代
while(fast_ptr != null && fast_ptr.next != null){
prev_ptr = slow_ptr;
slow_ptr = slow_ptr.next;
fast_ptr = fast_ptr.next.next;
}
//判断当slow_ptr = head时
if(prev_ptr != null){
prev_ptr.next = null;
}
return slow_ptr;
}
//第二个方法,进行高度平衡二叉搜索树的转换
public TreeNode sortedListToBST(ListNode head) {
if(head == null){
return null;
}
ListNode mid = this.findMiddleElement(head);
TreeNode node = new TreeNode(mid.val);
if (head == mid) {
return node;
}
node.left = this.sortedListToBST(head);
node.right = this.sortedListToBST(mid.next);
return node;
}
}