【Binary tree】Ordered linked list conversion binary search tree

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
}


small editor

Please add image description


Guess you like

Origin blog.csdn.net/xjh093/article/details/122960714