很简单的二分。代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
int len = num.length; | |
return build(num, 0, len - 1); | |
} | |
private TreeNode build(int[] num, int lo, int hi) { | |
if (lo > hi) | |
return null; | |
int mid = lo + (hi - lo) / 2; | |
TreeNode node = new TreeNode(num[mid]); | |
node.left = build(num, lo, mid - 1); | |
node.right = build(num, mid + 1, hi); | |
return node; | |
} | |
} |
No comments:
Post a Comment