LeetCode108 Convert Sorted Array to Binary Search Tree

详细见: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 = None

class 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值