本文主要是介绍leetcode oj java 108 Convert Sorted Array to Binary Search Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、问题描述:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
二、解决思路:
平衡BST的话,位于中间位置的节点当做ROOT, 可以保证平衡。中间节点的左边元素为左子树右边元素为右子树,递归即可。
三、代码:
package T12;/*** @author 作者 : xcy* @version 创建时间:2016年12月30日 下午2:31:19* 类说明*/
public class t108 {public static void main(String[] args) {// TODO Auto-generated method stubint[] nums = { 1, 2 };TreeNode root = sortedArrayToBST(nums);System.out.println("done!");}public static TreeNode sortedArrayToBST(int[] nums) {if (nums.length == 0) {return null;}if (nums.length == 1) {return new TreeNode(nums[0]);}TreeNode root = sortedArrayToBST(nums, 0, nums.length - 1);return root;}public static TreeNode sortedArrayToBST(int[] nums, int start, int end) {int num = end - start;if (num == 0) {return new TreeNode(nums[start]);}if (num == 1) {TreeNode root = new TreeNode(nums[end]);root.left = new TreeNode(nums[start]);return root;}// only two int mid = start + num / 2;TreeNode root = new TreeNode(nums[mid]);root.left = sortedArrayToBST(nums, start, mid - 1);root.right = sortedArrayToBST(nums, mid + 1, end);return root;}}
这篇关于leetcode oj java 108 Convert Sorted Array to Binary Search Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!