leetcode刷题笔记一百零九题 有序链表转换二叉搜索树
源地址:109. 有序链表转换二叉搜索树
问题描述:
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0 /
-3 9
/ /
-10 5
/**
本题在108题的基础上,进行了延伸,核心思想与108题基本一致,即获取区间的中间节点,作为根节点,递归其左子树区间与右子树区间。这里提供两种解法,快慢指针法和利用中序遍历思想
*/
//快慢指针,快指针每次向前2步,慢指针每次向前1步,这样当快指针到末尾时,慢指针正好指向中间结点
/**
* Definition for singly-linked list.
* class ListNode(var _x: Int = 0) {
* var next: ListNode = null
* var x: Int = _x
* }
*/
/**
* Definition for a binary tree node.
* class TreeNode(var _value: Int) {
* var value: Int = _value
* var left: TreeNode = null
* var right: TreeNode = null
* }
*/
object Solution {
def sortedListToBST(head: ListNode): TreeNode = {
def helper(head: ListNode): TreeNode = {
if (head == null) return null
if (head.next == null){
return new TreeNode(head.x)
}
var prev:ListNode = null
var slow = head
var fast = head
while (fast != null && fast.next != null){
prev = slow
slow = slow.next
fast = fast.next.next
}
prev.next = null
val root = new TreeNode(slow.x)
root.left = helper(head)
root.right = helper(slow.next)
return root
}
return helper(head)
}
}
//基于中序遍历的递归,基于先左后右的原则,且整个数组有序,故数组第一个节点为最左侧结点,则递归位置与结点顺序一致
/**
* Definition for singly-linked list.
* class ListNode(var _x: Int = 0) {
* var next: ListNode = null
* var x: Int = _x
* }
*/
/**
* Definition for a binary tree node.
* class TreeNode(var _value: Int) {
* var value: Int = _value
* var left: TreeNode = null
* var right: TreeNode = null
* }
*/
object Solution {
def sortedListToBST(head: ListNode): TreeNode = {
//获取结点个数
var length = 0
var startHelper = head
while (startHelper != null){
startHelper = startHelper.next
length += 1
}
var start = head
def helper(left: Int, right: Int): TreeNode = {
if (left > right) return null
val mid = (right + left + 1)/2
//先递归左侧,因为此时指针指向的永远是当前树中最左侧结点
val leftTree = helper(left, mid-1)
//构建树
val root = new TreeNode(start.x)
root.left = leftTree
start = start.next
root.right = helper(mid+1, right)
return root
}
return helper(0, length-1)
}
}