Contents

[Golang][Leetcode][BinaryTree]刷題系列-108-Convert Sorted Array to Binary Search Tree


108. Convert Sorted Array to Binary Search Tree


Level : Easy

原題連結 : Click

題目 :

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.


Example :

Note

Example 1:

Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3] Output: [3,1] Explanation: [1,3] and [3,1] are both a height-balanced BSTs.


解題思路 :

  • 這題需要我們將遞增序列的數列轉換成height-balacend的BST,題目定義為每一個node所連接的左右subtree之間深度不能差超過1
  • 其實呢這題考察我們對BST的熟悉度跟Recursive的熟練度
  • 若要左右高度相仿的subtree,那該root必須是該遞增序列的中位數才能使得左右subtree node數平均分布,然後每一個node都遵守與root一樣的準則寫出recursive code

Recursive解法

  • time complexity: O(n) , space complexity: O(1)

Runtime: 0 ms, faster than 100.00% of Go online submissions for Convert Sorted Array to Binary Search Tree.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sortedArrayToBST(nums []int) *TreeNode {
    
    if len(nums) == 0{
        return nil
    }
    
    left := 0
    right := len(nums)-1
    mid := (right + left)/2
    
    node := &TreeNode{
        Val: nums[mid],
        Left: sortedArrayToBST(nums[left:mid]),
        Right: sortedArrayToBST(nums[mid+1:right+1]),
    }
    
    return node
}

最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!