---
# System prepended metadata

title: 108. Convert Sorted Array to Binary Search Tree
tags: [binary search tree, leetcode, divide and conquer, binary tree]

---

# 108. Convert Sorted Array to Binary Search Tree

題目：<https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/>

解法：divide and conquer，取出中間值當作root，用左邊的陣列建成左子樹，用右
邊的陣列建成右子樹即可。

Python3：

``` python 3
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def listToTree(arr):
    nodes = [TreeNode(arr[0])]
    i = 0
    j = 1
    length = len(arr)
    while j < length:
        if arr[j] is not None:
            tmp = TreeNode(arr[j])
            nodes[i].left = tmp
            nodes.append(tmp)
        j += 1
        if j >= length:
            break
        if arr[j] is not None:
            tmp = TreeNode(arr[j])
            nodes[i].right = tmp
            nodes.append(tmp)
        j += 1
        i += 1
    return nodes[0]

def treeToList(root):
    if not root:
        return []
    from collections import deque
    nodes = deque()
    nodes.append(root)
    arr = []
    arr.append(root.val)
    while len(nodes):
        node = nodes.popleft()
        if node.left:
            nodes.append(node.left)
            arr.append(node.left.val)
        else:
            arr.append(None)
        if node.right:
            nodes.append(node.right)
            arr.append(node.right.val)
        else:
            arr.append(None)
    return arr

class Solution:
    def sortedArrayToBST(self, nums: list[int]) -> TreeNode:
        if nums:
            length = len(nums)
            idx = length // 2
            root = TreeNode(nums[idx])
            root.left = self.sortedArrayToBST(nums[:idx])
            root.right = self.sortedArrayToBST(nums[idx+1:])
            return root

if __name__ == '__main__':
    nums = [-10,-3,0,5,9]
    
    ans = Solution().sortedArrayToBST(nums)
    print(treeToList(ans))
```

C：

``` c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

struct TreeNode* strToTree(char *str) {
    char *token = strtok(str, ",");
    struct TreeNode **nodes = (struct TreeNode**)malloc(sizeof(struct TreeNode*));
    nodes[0] = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    nodes[0]->val = atoi(token);
    nodes[0]->left = NULL;
    nodes[0]->right = NULL;
    int i = 0, len = 1;
    token = strtok(NULL, ",");
    while (token != NULL) {
        if (strcmp(token, "null") != 0) {
            len++;
            nodes = (struct TreeNode**)realloc(nodes, sizeof(struct TreeNode*) * len);
            nodes[len - 1] = (struct TreeNode*)malloc(sizeof(struct TreeNode));
            nodes[len - 1]->val = atoi(token);
            nodes[len - 1]->left = NULL;
            nodes[len - 1]->right = NULL;
            nodes[i]->left = nodes[len - 1];
        }
        token = strtok(NULL, ",");
        if (token == NULL)
            break;
        if (strcmp(token, "null") != 0) {
            len++;
            nodes = (struct TreeNode**)realloc(nodes, sizeof(struct TreeNode*) * len);
            nodes[len - 1] = (struct TreeNode*)malloc(sizeof(struct TreeNode));
            nodes[len - 1]->val = atoi(token);
            nodes[len - 1]->left = NULL;
            nodes[len - 1]->right = NULL;
            nodes[i]->right = nodes[len - 1];
        }
        token = strtok(NULL, ",");
        i++;
    }
    return nodes[0];
}

void printLevelOrderWithNull(struct TreeNode* root) {
    struct TreeNode * bfs[10000] = {};
    bfs[0] = root;
    int i = 0, len = 1;
    printf("%d ", root->val);
    while (i < len) {
        if (bfs[i]->left != NULL) {
            bfs[len++] = bfs[i]->left;
            printf("%d ", bfs[i]->left->val);
        } else
            printf("null ");
        if (bfs[i]->right != NULL) {
            bfs[len++] = bfs[i]->right;
            printf("%d ", bfs[i]->right->val);
        } else
            printf("null ");
        i++;
    }
    printf("\n");
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    if (numsSize == 0)
        return NULL;
    int idx = numsSize / 2;
    struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->val = nums[idx];
    root->left = sortedArrayToBST(nums, idx);
    root->right = sortedArrayToBST(nums + idx + 1, numsSize - idx - 1);
    return root;
}

int main()
{
    int nums[] = {-10,-3,0,5,9};
    int numsSize = sizeof(nums) / sizeof(nums[0]);
    
    struct TreeNode* ans = sortedArrayToBST(nums, numsSize);
    printLevelOrderWithNull(ans);
    return 0;
}
```

###### tags: `leetcode` `binary tree` `binary search tree` `divide and conquer`
