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

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

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

基本上一次过,要注意边界条件的问题:如果在recursion里有两个参数int begin, end, 递归写作recursion(num, mid+1, end), 因为+号的原因,递归中是会出现begin > end 的情况的,所以考虑初始条件的时候应该要考虑充分。

1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public TreeNode sortedArrayToBST(int[] num) {12         if (num == null || num.length == 0) return null;13         return construct(num, 0, num.length - 1);14     }15     16     public TreeNode construct(int[] num, int begin, int end) {17         if (begin > end) return null; 19         int mid = (begin + end) / 2;20         TreeNode root = new TreeNode(num[mid]);21         root.left = construct(num, begin, mid-1);22         root.right = construct(num, mid+1, end);23         return root;24     }25 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/3746865.html

你可能感兴趣的文章
mysql表之间的关系及级联操作
查看>>
mac 搭建virtualenv的那些坑
查看>>
多路复用IO模型
查看>>
并发、串行、并行及多道技术原理
查看>>
hashlib、pickle、hmac、logging模块使用
查看>>
javascript常用知识点总结
查看>>
2019秋招复习笔记--数据库基本操作
查看>>
2019秋招复习笔试--手写代码
查看>>
2019秋招复习笔记--智力题
查看>>
MySQL学习笔记
查看>>
2019秋招面试复习 项目重点提问
查看>>
面试题
查看>>
DS博客作业08-课程总结
查看>>
利用Python爬虫刷店铺微博等访问量最简单有效教程
查看>>
浅谈软件测试与墨菲定律
查看>>
文件安全复制之 FastCopy
查看>>
强烈推荐美文之《从此刻起,我要》
查看>>
MYSQL中数据类型介绍
查看>>
评估软件上线标准
查看>>
敏捷开发流程
查看>>