108-Convert Sorted Array to Binary Search Tree
Description
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
問題描述
給定一個元素為遞增序列的陣列, 將其轉換為平衡二叉排序樹
平衡二叉排序樹定義為, 每個節點的左右子樹的高度之差不大於1
問題分析
每次取陣列的中間元素作為當前節點即可
解法
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null || nums.length == 0) return null;
return getTreeNode(nums, 0, nums.length - 1);
}
private TreeNode getTreeNode(int[] nums, int start, int end){
//注意這裡
if(start > end) return null;
//取中間元素作為當前節點
int middle = start + (end - start) / 2;
TreeNode n = new TreeNode(nums[middle]);
//注意start和end的變化
n.left = getTreeNode(nums, start, middle - 1);
n.right = getTreeNode(nums, middle + 1, end);
return n;
}
}
相關文章
- [leetcode]convert-sorted-array-to-binary-search-treeLeetCode
- Java for LeetCode 109 Convert Sorted List to Binary Search TreeJavaLeetCode
- [LeetCode] 109. Convert Sorted List to Binary Search TreeLeetCode
- # Search in Rotated Sorted Array
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- 【刷題】Search in a Big Sorted Array
- 173. Binary Search Tree Iterator
- 669-Trim a Binary Search Tree
- LeetCode 98. Validate Binary Search TreeLeetCode
- 501-Find Mode in Binary Search Tree
- [LeetCode] 702. Search in a Sorted Array of Unknown SizeLeetCode
- [LeetCode] 501. Find Mode in Binary Search TreeLeetCode
- 235-Lowest Common Ancestor of a Binary Search Tree
- LeetCode 501. Find Mode in Binary Search TreeLeetCode
- 二分搜尋樹(Binary Search Tree)
- 二叉搜尋樹(Binary Search Tree)(Java實現)Java
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- Traversals of binary tree
- 如何在Java中實現二叉搜尋樹( binary search tree)?Java
- 88. Merge Sorted Array
- 977. Squares of a Sorted Array
- Leetcode Binary Tree PathsLeetCode
- Leetcode 88. Merge Sorted ArrayLeetCode
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- Remove-duplicates-from-sorted-arrayREM
- [LintCode] Binary Tree Level Order
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 543-Diameter of Binary Tree
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 226-Invert Binary Tree