首页 > 其他 > 详细

LeetCode Convert Sorted Array to Binary Search Tree

时间:2015-05-05 21:58:02      阅读:122      评论:0      收藏:0      [点我收藏+]

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

题意:将一个有序数组变成二叉搜索树。

思路:简单的递归。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private TreeNode build(int[] nums, int start, int end) {
		if (start > end) return null;
		int mid = start + end >> 1;
		TreeNode root = new TreeNode(nums[mid]);
		root.left = build(nums, start, mid-1);
		root.right = build(nums, mid+1, end);
		return root;
	} 
	
    public TreeNode sortedArrayToBST(int[] nums) {
    	return build(nums, 0, nums.length-1);
    }
}



LeetCode Convert Sorted Array to Binary Search Tree

原文:http://blog.csdn.net/u011345136/article/details/45506833

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!