LeetCode108_Convert SortedArray to BinarySearchTree(将有序数组转成二叉排序树) Java题解

题目:

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

题解:

和我上面一篇将有序链表转成二叉排序树中用哈希表解的方法是一样的。基本思路:链表中间那个节点为树的根节点。根节点的左子树节点应该是根节点左边那部分的中间节点,根节点的右节点应该是根节点右边那部分链表的中间节点。后面就依照这个规律依次类推了。

public static TreeNode sortedArrayToBST(int[] nums) {
		 int end=nums.length;
		 if(end<=0)
			 return null;
		 return buildTree(nums, 0, end-1);//由于从0開始计数 所以减一
		 
	        
	    }
	 public static TreeNode buildTree(int[] nums,int start,int end)
	 {
		 if(start<=end)
		 {
			 int mid=(start+end)/2;
			 TreeNode root=new TreeNode(nums[mid]);
			 root.left=buildTree(nums, start, mid-1);
			 root.right=buildTree(nums, mid+1, end);
			 return root;
		 }
		 else {
			return null;
		}
		 
	 }


原文地址:https://www.cnblogs.com/liguangsunls/p/7261305.html