0x00 topic
Given a 单
linked list
whose elements are 升序
sorted
, convert it into a highly balanced 二叉搜索
tree
A 高度平衡
binary tree means that the absolute value
of the 左右
two tree
高度差
does not exceed1
0x01 Ideas
This problem is similar to converting an ordered array to a binary search tree
The feature of first 链表
converting to 数组
二叉搜索树
is:
if [in-order traversal] binary search tree, the result is an 升序
array
The [middle number] of an ordered array 根节点
左
is the sequence of 左子树
右
edges is the sequence of the root node The 右子树
sequence so on. Therefore, the [dichotomy] can be used to solve the problem
0x02 solution
language:Swift
tree node:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
solution:
func sortedListToBST(_ head: ListNode?) -> TreeNode? {
if head == nil { return nil }
// 将 链表 转换成 数组
var tmp = head
var arr: [Int] = []
while tmp != nil {
arr.append(tmp!.val)
tmp = tmp?.next
}
// 有序数组 转换为 二叉搜索树
return toBST(arr, 0, arr.count - 1)
}
func toBST(_ nums: [Int], _ left: Int, _ right: Int) -> TreeNode? {
if left > right { return nil }
let mid = (left + right) / 2
let val = nums[mid]
// 根节点
let node = TreeNode(val)
// 左子树
node.left = toBST(nums, left, mid - 1)
// 右子树
node.right = toBST(nums, mid + 1, right)
return node
}