Convert Sorted Array to Binary Search Tree
来源:互联网 发布:唐嫣王晶 知乎 编辑:程序博客网 时间:2024/05/10 23:37
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
public class Solution {public TreeNode sortedArrayToBST(int[] num) {if (num == null) return null;return arrayToBST(num, 0, num.length - 1);}private TreeNode arrayToBST(int[] num, int l, int r) {if (l > r) return null;int m = (l + r) / 2;TreeNode cur = new TreeNode(num[m]);cur.left = arrayToBST(num, l, m - 1);cur.right = arrayToBST(num, m + 1, r);return cur;}}
IDEA:
Use data, in the range (l, r), to construct the current tree. First pick the middle element as the value of root. Then recursively construct the left sub-tree using data (i, m-1), and the right sub-tree(m+1, r). The initial condition is (1) i > j, the sub-tree being constructed is null, or (2) the sub-tree being constructed is a leaf (already included in case 1).
0 0
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- git不能上传空目录
- [转载] AOE网关键路径的计算
- poj1050 最大子矩阵和
- Linux驱动下的platform总线架构(转)
- Verilog的I2C实现
- Convert Sorted Array to Binary Search Tree
- ZOJ 3904 Beer Problem 最大费用最大流
- 安卓之旅(2)--添加一个ActionBar(2)
- HDOJ1015看懂题之后的简单粗暴
- github&git的使用经验
- php实现采集电影数据
- hdoj problem 1272小希的迷宫 (并查集&&动态规划)
- C语言--Friends and Present
- Mongodb入门——安装与配置