- 108. Convert Sorted Array to Bin
- leetcode:108. Convert Sorted Arr
- LeetCode 108. Convert Sorted Arr
- Leetcode 108. Convert Sorted Arr
- LeetCode 108. Convert Sorted Arr
- Leetcode-108Convert Sorted Array
- [leetcode] 108. Convert Sorted A
- Leetcode PHP题解--D95 108. Convert
- [LeetCode]108. Convert Sorted Ar
- [leetcode]108. Convert Sorted Ar
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题意,给我一个升序的数组,让我构建一棵平衡的二叉树。
解析:利用递归的方式,每次选取一个中间位置的数,放在这棵二叉树上。
java代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) return null;
return buildTree(nums, 0, nums.length - 1);
}
private TreeNode buildTree(int[] nums, int lo, int hi) {
if (lo > hi) {
return null;
}
int mid = lo + (hi - lo) / 2;
int data = nums[mid];
TreeNode treeNode = new TreeNode(data);
treeNode.left = buildTree(nums, lo, mid - 1);
treeNode.right = buildTree(nums, mid + 1, hi);
return treeNode;
}
}
网友评论