LeetCode 108 Convert Sorted Array to Binary Search Tree

栏目: 编程工具 · 发布时间: 7年前

内容简介:给予一个从小到大的数组, 构建一颗二叉平衡树, 即每个节点的两个子树的深度不能相差超过 1.例 :这道题有点类似于二分查找法, 即对二叉搜索树的反向推导, 每次取数组最中间的节点最为中节点, 左侧为左子树的内容, 右侧为右子树的内容, 直到不再存在子树.

给予一个从小到大的数组, 构建一颗二叉平衡树, 即每个节点的两个子树的深度不能相差超过 1.

例 :

给予数组: [-10, -3, 0, 5, 9]

返回以下树都是符合条件的: 
      0
     / \
   -3   9
   /   /
 -10  5


      0
    /  \
  -10   5
    \    \
    -3    9

解法

这道题有点类似于二分查找法, 即对二叉搜索树的反向推导, 每次取数组最中间的节点最为中节点, 左侧为左子树的内容, 右侧为右子树的内容, 直到不再存在子树.

import util.TreeNode;

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

    private TreeNode helper(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }

        int mid = (start + end) / 2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = helper(nums, start, mid - 1);
        node.right = helper(nums, mid + 1, end);
        return node;
    }
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Convert Sorted Array to Binary Search Tree. Memory Usage: 35.8 MB, less than 99.88% of Java online submissions for Convert Sorted Array to Binary 

以上所述就是小编给大家介绍的《LeetCode 108 Convert Sorted Array to Binary Search Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Agile Web Development with Rails, Third Edition

Agile Web Development with Rails, Third Edition

Sam Ruby、Dave Thomas、David Heinemeier Hansson / Pragmatic Bookshelf / 2009-03-17 / USD 43.95

Rails just keeps on changing. Rails 2, released in 2008, brings hundreds of improvements, including new support for RESTful applications, new generator options, and so on. And, as importantly, we’ve a......一起来看看 《Agile Web Development with Rails, Third Edition》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试