领扣LintCode算法问题答案-1359. 有序数组转换为二叉搜索树
发布日期:2021-06-30 17:10:55
浏览次数:2
分类:技术文章
本文共 1766 字,大约阅读时间需要 5 分钟。
领扣LintCode算法问题答案-1359. 有序数组转换为二叉搜索树
目录
1359. 有序数组转换为二叉搜索树
描述
给定一个数组,其中元素按升序排序,将其转换为高度平衡的BST。
对于这个问题,高度平衡的二叉树被定义为二叉树,其中每个节点的两个子树的深度从不相差超过1。
样例 1:
输入: [-10,-3,0,5,9],输出: [0,-3,9,-10,#,5],解释:针对该数组的其中一个解为 [0,-3,9,-10,null,5], 其对应的平衡BST树如下: 0 / \ -3 9 / / -10 5
样例 2:
输入: [1,3]输出: [3,1]解释:针对该数组的其中一个解为 [3,1], 其对应的平衡BST树如下: 3 / 1
题解
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param nums: the sorted array * @return: the root of the tree */ public TreeNode convertSortedArraytoBinarySearchTree(int[] nums) { // Write your code here. if (nums == null || nums.length == 0) { return null; } int mid = (nums.length - 1) / 2; TreeNode root = new TreeNode(nums[mid]); root.left = convertSortedArraytoBinarySearchTree(nums, 0, mid - 1); root.right = convertSortedArraytoBinarySearchTree(nums, mid + 1, nums.length - 1); return root; } private TreeNode convertSortedArraytoBinarySearchTree(int[] nums, int startIndex, int endIndex) { if (startIndex > endIndex || startIndex < 0 || endIndex >= nums.length) { return null; } int mid = (startIndex + endIndex) / 2; TreeNode root = new TreeNode(nums[mid]); root.left = convertSortedArraytoBinarySearchTree(nums, startIndex, mid - 1); root.right = convertSortedArraytoBinarySearchTree(nums, mid + 1, endIndex); return root; }}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。
转载地址:https://le-yi.blog.csdn.net/article/details/108916000 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月21日 10时37分58秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
十二时辰篇:这该死的 996
2019-04-30
2021最新 上海互联网公司排名
2019-04-30
字节vs快手!取消大小周之战
2019-04-30
送一个闲置显示器!
2019-04-30
Oracle 行转列 pivot函数基本用法
2019-04-30
Oracle字符串分隔符替换(替换奇数个或偶数个)
2019-04-30
Oracle 利用 UTL_SMTP 包发送邮件
2019-04-30
Oracle 自定义函数实现split功能,支持超长字符串和clob类型的分隔
2019-04-30
Oracle 的循环中的异常捕捉和处理
2019-04-30
Oracle通过pivot和unpivot配合实现行列转换
2019-04-30
给Oracle数据库换一个1522端口的监听
2019-04-30
Excel表格数据生成ECharts图表
2019-04-30
阿里云短信服务python版,pyinstaller打包运行时缺少文件
2019-04-30
Oracle的pfile和spfile的一点理解和笔记
2019-04-30
WebService的简单案例记录(Java)
2019-04-30
Html利用PHP与MySQL交互
2019-04-30
dos简单命令
2019-04-30
mysql的安装与卸载与Navicat远程连接
2019-04-30
java实现稀疏数组及将稀疏数组存入硬盘中
2019-04-30