Giter Club home page Giter Club logo

algo-notes's People

Contributors

hoomjac avatar

Watchers

 avatar  avatar

algo-notes's Issues

leetcode-108. 将有序数组转换为二叉搜索树

题目

将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定有序数组: [-10,-3,0,5,9],

一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

  1. 取数组中点,建立根节点,并把数组切分成左右两半
  2. 建立左子树:取数组左半边中点,递归重复以上步骤
  3. 建立右子树:取数组右半边中点,递归重复以上步骤
  4. 直到数组开始的索引大于结束索引,返回null,跳出递归

代码

var sortedArrayToBST = function(nums) {
    
    return buildNode(nums,0,nums.length - 1)

    function buildNode(nums,start,end) {
        if(start > end) return null
        let mid = (start + end) >>> 1
        let root = new TreeNode(nums[mid])
        root.left = buildNode(nums,start,mid - 1)
        root.right = buildNode(nums,mid + 1,end)
        return root
    }
};

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.