博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LC.108.Convert Sorted Array to Binary Search Tree
阅读量:6568 次
发布时间:2019-06-24

本文共 1284 字,大约阅读时间需要 4 分钟。

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:       0      / \    -3   9    /   /  -10  5 time: o(n) space: o(height) pre order: 先弄自己, 再管下面的兄弟
public TreeNode sortedArrayToBST(int[] nums) {        if (nums  == null || nums.length ==0 )return null ;        int left = 0, right = nums.length -1 ;        return helper(nums, left, right);    }    //everytime create the root and connect to left and right    private TreeNode helper(int[] nums, int left, int right) {        int mid = left + (right - left) /2 ;        TreeNode node = new TreeNode(nums[mid]) ;        if (mid+ 1<=right){            node.right = helper(nums, mid+1, right) ;        }        if (mid -1 >= left){            node.left = helper(nums, left, mid-1) ;        }        //going down and repeat        return node ;    }

 

 

转载于:https://www.cnblogs.com/davidnyc/p/8495669.html

你可能感兴趣的文章
mysql优化
查看>>
【批处理】for循环中产生不同的随机数
查看>>
Gradle -help
查看>>
/etc/security/limits.conf
查看>>
js 框架
查看>>
android 实现ListView中添加RaidoButton单选
查看>>
Oracle数据库:启动操作
查看>>
linux下的防火墙
查看>>
SNAT与DNAT
查看>>
Linux 修改密码“ Authentication token manipulation err”
查看>>
openstack
查看>>
Lync Server 2013 安装体验(一)
查看>>
EBB-24、DNS2
查看>>
css3做的nav
查看>>
汇编笔记
查看>>
点击qq、点击邮箱01
查看>>
时间处理总结(三)javascript与WCF
查看>>
Ubantu下安装jdk 教程
查看>>
ActiveMQ入门实例
查看>>
linux安装至少有哪两个分区,各自作用是什么?
查看>>