您的位置:首页 > 其它

Leetcode: Convert Sorted Array to Binary Search Tree

2014-09-21 13:34 447 查看
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Pick the middle element of the array as a head node, use recursion to set the left and right nodes.

/**
* 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) {
if (num == null) {
return null;
}

return buildBST(num, 0, num.length - 1);
}

private TreeNode buildBST(int[] num, int start, int end) {
if (start > end) {
return null;
}

TreeNode node = new TreeNode(num[(start + end) / 2]);
node.left = buildBST(num, start, (start + end) / 2 - 1);
node.right = buildBST(num, (start + end) / 2 + 1, end);
return node;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode