题解 | #判断二叉树是否对称#

将升序数组转化为平衡二叉搜索树

http://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d

需要用的方法为--递归分治法。
import java.util.*;

/*

  • public class TreeNode {
  • int val = 0;
  • TreeNode left = null;
  • TreeNode right = null;
  • }
  • /

public class Solution {
/**
*
* @param num int整型一维数组
* @return TreeNode类
*/
public TreeNode sortedArrayToBST (int[] num) {
// write code here
if(num == null || num.length == 0){
return null;
}
int n = num.length;
int mid = n/2;
TreeNode node = new TreeNode(num[mid]);
int [] numLeft = new int [mid];
int []numRight = new int [n-mid-1];
for(int i = 0 ; i<mid ; i++){
numLeft[i] = num[i];
}
for(int i = mid+1 ; i<n ; i++){
numRight[i-mid-1] = num[i];
}
node.left = sortedArrayToBST(numLeft);
node.right = sortedArrayToBST(numRight);
return node;
}
}

全部评论
走错片场啦兄嘚^_^
点赞 回复 分享
发布于 2021-08-10 23:21

相关推荐

06-07 00:00
已编辑
腾讯_后端开发
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务