LeetCode108 Convert Sorted Array to Binary Search Tree

来源:互联网 发布:python交易策略 编辑:程序博客网 时间:2024/06/07 19:57

详细见:leetcode.com/problems/convert-sorted-array-to-binary-search-tree


Java Solution: github

package leetcode;import tools.TreeNode辅助.TreeNode;/* * Given an array where elements are sorted in ascending order,  * convert it to a height balanced BST. */public class P108_ConvertSortedArraytoBinarySearchTree {public static void main(String[] args) {}/* * AC * 1 ms */static class Solution {    public TreeNode sortedArrayToBST(int[] nums) {        if (nums == null || nums.length == 0) {        return null;        }        return sortedArrayToBST(nums, 0, nums.length - 1);    }private TreeNode sortedArrayToBST(int[] nums, int i, int j) {if (i > j) {return null;}if (i == j) {return new TreeNode(nums[i]);}int root_index = (i + j) / 2;TreeNode root = new TreeNode(nums[root_index]);root.left = sortedArrayToBST(nums, i, root_index - 1);root.right = sortedArrayToBST(nums, root_index + 1, j);return root;}}}


C Solution: github

/*    url: leetcode.com/problems/convert-sorted-array-to-binary-search-tree    AC 6ms 36.54%*/#include <stdio.h>#include <stdlib.h>struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;};typedef struct TreeNode stn;typedef struct TreeNode * ptn;ptn tn_init(int val) {    ptn n = (ptn) malloc(sizeof(stn));    n->left = NULL;    n->right = NULL;    n->val = val;    return n;}ptn search(int* n, int ni, int nj) {    ptn root = NULL;    int nm = (ni+nj)/2;    if (ni > nj) return NULL;    root = tn_init(n[nm]);    root->left = search(n, ni, nm-1);    root->right = search(n, nm+1, nj);    return root;}ptn sortedArrayToBST(int* n, int nn) {    return search(n, 0, nn-1);}


Python Solution: github

#coding=utf-8'''    url: leetcode.com/problems/convert-sorted-array-to-binary-search-tree    @author:     zxwtry    @email:      zxwtry@qq.com    @date:       2017年4月28日    @details:    Solution: 145ms 9.81%'''class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def search(self, n, ni, nj):        if ni > nj: return None        nm = (ni+nj) // 2        root = TreeNode(n[nm])        root.left = self.search(n, ni, nm-1)        root.right = self.search(n, nm+1, nj)        return root        def sortedArrayToBST(self, n):        """        :type n: List[int]        :rtype: TreeNode        """        nn = 0 if n == 0 else len(n)        return self.search(n, 0, nn-1)        


0 0