leetcode 108. Convert Sorted Array to Binary Search Tree

原创 2016年06月01日 11:49:30

题目内容
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题目分析
给定一个排好序的数组,然后将其转换成最平衡的二叉查找树。
根据二叉查找树的特点,左孩子都小于父节点,右孩子都大于父节点。所以,可以直接利用排序好的数组,取数组中间下标的值,不断作为左右孩子的父节点,通过递归可以实现。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return help(nums,0,nums.length-1);
    }

    public TreeNode help(int[] nums,int l,int r){
        if(l>r) return null;
        if(l==r) return new TreeNode(nums[l]);
        int mid=(l+r)/2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left=help(nums , l ,mid-1);
        root.right=help(nums,mid+1,r);
        return root;
    }
}

相关文章推荐

LeetCode 108, 109. Convert Sorted Array/List to Binary Search Tree

1. 题目描述 Given an array where elements are sorted in ascending order, convert it to a height bal...

LeetCode(108)Convert Sorted Array to Binary Search Tree

题目如下: 分析如下: 递归进行。每次找到排序数组的中点,中点左边的子排序数组构成左子树,中点右边的子排序数组构成右子树。就这样递归进行。由于每次都几乎做到了二分,所以每次的左子树和右子树的节点数量是...

LeetCode108 Convert Sorted Array to Binary Search Tree

详细见:leetcode.com/problems/convert-sorted-array-to-binary-search-tree Java Solution: github p...
  • zxwtry
  • zxwtry
  • 2017年04月28日 22:04
  • 117

【LeetCode-面试算法经典-Java实现】【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】

【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  ...

leetcode108~Convert Sorted Array to Binary Search Tree

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

Leetcode 108 Convert Sorted Array to Binary Search Tree 有序数组构造平衡二叉查找树

给出一个有序数组(递增),使用该数组构造一个平衡二叉查找树。

[leetcode]108. Convert Sorted Array to Binary Search Tree@Java解题报告

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ Given a...

【LeetCode】108. Convert Sorted Array to Binary Search Tree 解法及注释,分治法,递归

108. Convert Sorted Array to Binary Search Tree Total Accepted: 73365 Total Submissions: 197776 Di...

LeetCode- 108/109. Convert Sorted Array/List to Binary Search Tree (JAVA)

LeetCode- 108/109. Convert Sorted Array/List to Binary Search Tree (JAVA),109. Convert Sorted List ...

[LeetCode]108. Convert Sorted Array to Binary Search Tree(升序数组转化为平衡二叉树)

108. Convert Sorted Array to Binary Search Tree原题链接 Given an array where elements are sorted in asc...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 108. Convert Sorted Array to Binary Search Tree
举报原因:
原因补充:

(最多只允许输入30个字)