跳至主要內容

108. 将有序数组转换为二叉搜索树

T4mako算法二叉搜索树分治数组二叉树小于 1 分钟

108. 将有序数组转换为二叉搜索树

简单

解法:递归

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
		int i = nums.length / 2;
		TreeNode res = new TreeNode(nums[i]);
		res.left = build(nums,0,i - 1);
		res.right = build(nums,i + 1,nums.length - 1);
		return res;
    }

	public TreeNode build(int[] nums, int left, int right) {
		if(left > right) return null;
		else {
			int i = (left + right) / 2;
			TreeNode node = new TreeNode(nums[i]);
			node.left = build(nums,left,i - 1);
			node.right = build(nums,i + 1,right);
			return node;
		}
	}
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5