树Convert Sorted Array to Binary Search Tree
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树Convert Sorted Array to Binary Search Tree相关的知识,希望对你有一定的参考价值。
题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:
找到数组的中间数据作为根节点,小于中间数据的数组来构造作为左子树,大于中间数据的数组来构造右子树。
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {number[]} nums * @return {TreeNode} */ var sortedArrayToBST = function(nums) { var len=nums.length; if(len==0){ return null; } return BuildTree(nums,0,len-1); }; function BuildTree(nums,s,e){ if(s>e){ return null; } if(s==e){ return new TreeNode(nums[s]); } var middle=(s+e)/2; var rootval=nums[middle]; var root=new TreeNode(rootval); root.left=BuildTree(nums,s,middle-1); root.right=BuildTree(nums,middle+1,e); return root; }
以上是关于树Convert Sorted Array to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree
[leetcode]108. Convert Sorted Array to Binary Search Tree构建二叉搜索树
LeetCode Convert Sorted Array to Binary Search Tree
LeetCode 108. Convert Sorted Array to Binary Search Tree (有序数组转化为二叉搜索树)