递归---Convert Sorted Array to Binary Search Tree With Minimal Height
2016-01-25 14:54
519 查看
Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.
Have you met this question in a real interview? Yes
Example
Given [1,2,3,4,5,6,7], return
4
/ \
2 6
/ \ / \
1 3 5 7
Note
There may exist multiple valid solutions, return any of them.
Tags Expand
Have you met this question in a real interview? Yes
Example
Given [1,2,3,4,5,6,7], return
4
/ \
2 6
/ \ / \
1 3 5 7
Note
There may exist multiple valid solutions, return any of them.
Tags Expand
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param A: an integer array * @return: a tree node */ private TreeNode buildTree(int[] num, int start, int end) { if (start > end) { return null; } TreeNode node = new TreeNode(num[(start + end) / 2]); node.left = buildTree(num, start, (start + end) / 2 - 1); node.right = buildTree(num, (start + end) / 2 + 1, end); return node; } public TreeNode sortedArrayToBST(int[] A) { // write your code here if (A == null) { return null; } return buildTree(A, 0, A.length - 1); } }
相关文章推荐
- 看大神解释https和http的概念和区别
- hadoop 2.6.0 安全问题--UserGroupInformation
- Entity Framework 教程
- mysql 连接字符串与SQL不同(mysql CONCAT()的使用)
- RHCE 学习笔记(13) RPM 和 YUM
- jsp截取字符串
- python算法——第四天
- LA 3523 tarjian求双连通分量+二分判奇圈
- jQuery中inArray方法注意事项分析
- 沉湎网络 心理障碍
- leetcode之Add Binary
- 自动生成android、ios开发所需要的所有尺寸的图片
- cocos2d-x3.2中加入Android手机震动
- 3D文字菜单变换
- 解决android studio设置版本号
- C++ template —— 模板特化(五)
- ---------很简单的 一道 堆栈问题-------
- linux 乱码问题解决
- PtrClassicFrameLayout 下拉刷新控件
- Android之数据持久化三(sqllite数据库)三