首页 > 其他 > 详细

LeetCode | Convert Sorted Array to Binary Search Tree

时间:2014-03-10 22:55:38      阅读:492      评论:0      收藏:0      [点我收藏+]

题目

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

分析

数组元素可以直接定位,比Convert Sorted List to Binary Search Tree要好写点。

代码

public class ConvertSortedArrayToBinarySearchTree {
	public TreeNode sortedArrayToBST(int[] num) {
		if (num == null || num.length == 0) {
			return null;
		}

		int N = num.length;
		return solve(num, 0, N - 1);
	}

	private TreeNode solve(int[] num, int low, int high) {
		if (low > high) {
			return null;
		}
		int mid = low + (high - low) / 2;
		TreeNode root = new TreeNode(num[mid]);
		root.left = solve(num, low, mid - 1);
		root.right = solve(num, mid + 1, high);
		return root;
	}
}


LeetCode | Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com

LeetCode | Convert Sorted Array to Binary Search Tree

原文:http://blog.csdn.net/perfect8886/article/details/20951185

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