描述
给定一个升序排序的数组,将其转化为平衡二叉搜索树(BST).
平衡二叉搜索树指树上每个节点 node 都满足左子树中所有节点的的值都小于 node 的值,右子树中所有节点的值都大于 node 的值,并且左右子树的节点数量之差不大于1
数据范围:0≤n≤10000,数组中每个值满足 0∣val∣≤5000
进阶:空间复杂度 O(n) ,时间复杂度 O(n)
该题时数据结构中比较基础的题目,但是在java语法上出现了一些错误,比如Thread root=new Thread(root.val);与root =new Thread(root.val);不同,前者是新建立一个引用,后者是将一片存储空间分配给赋给一个引用。并且,java和C语言的语法是类似的,函数的形式参数只有用return语句返回后才会生效,如果想要同时返回多个值,可以考虑使用全局变量。
public class Solution {
/**
*
* @param num int整型一维数组
* @return TreeNode类
*/
public TreeNode sortedArrayToBST (int[] num) {
// write code here
int len=num.length;
if (len==0) return null;
int mid=len/2;
TreeNode root= new TreeNode(num[mid]);
root.val=num[mid];
for (int i=0;i<len;i++)
{
if(i==len/2) continue;
Insert(root,num[i]);
}
return root;
}
public TreeNode Insert(TreeNode root,int num)
{
if(root==null)
{ root=new TreeNode(num);
root.left=null;
root.right=null;
}
else if(num>root.val)
{
root.right=Insert(root.right,num);
}
else if(num<root.val)
{
root.left=Insert(root.left,num);
}
return root;
}
}