Convert Sorted Array to Binary Search Tree - Leetcode
2015-02-26 12:31
627 查看
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedArrayToBST(int[] num) { return sortedArrayToBSTHelper(0,num.length-1,num); } private TreeNode sortedArrayToBSTHelper(int start, int end, int[] num){ int len = end-start+1; if(len <= 0) return null; int mid = start+len/2; TreeNode root= new TreeNode(num[mid]); root.left = sortedArrayToBSTHelper(start, mid-1, num); root.right = sortedArrayToBSTHelper(mid+1, end, num); return root; } }
分析,用笔画一下,就发现,你要构造一个树先确定他的root, 即中值。然后找root的左/右子树,也就是继续在左/右边区域找中值,直到所有值都安排到相应的位置了。
Given an array where elements are sorted in ascending order, convert it to a
height balanced BST.
相关文章推荐
- [LeetCode] Convert Sorted Array to Binary Search Tree, Solution
- leetcode 11: Convert Sorted Array to Binary Search Tree
- leetcode - Convert Sorted Array to Binary Search Tree
- [leetcode刷题系列]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- leetcode -- Convert Sorted Array to Binary Search Tree
- [leetcode] Convert Sorted Array to Binary Search Tree
- [Leetcode 32] 108 Convert Sorted Array to Binary Search Tree
- LeetCode_Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- [Leetcode] Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- leetcode 11: Convert Sorted Array to Binary Search Tree
- leetcode: Convert Sorted Array to Binary Search Tree
- arrayfunction[LeetCode]Convert Sorted Array to Binary Search Tree
- [LeetCode]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree