Problem:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
先序遍历。
Solution:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int[] gnum;
public TreeNode sortedArrayToBST(int[] num) {
gnum = num;
return subBST(0, num.length);
}
private TreeNode subBST(int start,int len)
{
if(len==0)
return null;
TreeNode root = new TreeNode(0);
root.val = gnum[start+len/2];
root.left = subBST(start, len/2);
root.right = subBST(start+len/2+1, (len-1)/2);
return root;
}
}
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int[] gnum;
public TreeNode sortedArrayToBST(int[] num) {
gnum = num;
return subBST(0, num.length);
}
private TreeNode subBST(int start,int len)
{
if(len==0)
return null;
TreeNode root = new TreeNode(0);
root.val = gnum[start+len/2];
root.left = subBST(start, len/2);
root.right = subBST(start+len/2+1, (len-1)/2);
return root;
}
}