Leetcode108——Convert Sorted Array to Binary Search Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

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

2. 求解

这个题主要是根据一个有序数组构造二叉查找树(树的左结点小于根节点,根节点小于右结点,子树具有同样的性质)。构造方法主要是递归,每次构建子树时都需要将数组分成左右两半,左边的构建左子树,右边的构建右子树,中间元素构造根节点。其实有序数组是二叉查找树的中序遍历。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return buildBinarySearchTree(nums, 0, nums.length - 1);
}

public TreeNode buildBinarySearchTree(int[] nums, int start, int end) {
if(start > end) {
return null;
}
int mid = (start + end) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildBinarySearchTree(nums, start, mid - 1);
root.right = buildBinarySearchTree(nums, mid + 1, end);
return root;
}
}
如果有收获,可以请我喝杯咖啡!