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
原创粉丝点击