Leetcode108——Convert Sorted Array to Binary Search Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

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

2. 求解

这个题主要是根据一个有序数组构造二叉查找树(树的左结点小于根节点,根节点小于右结点,子树具有同样的性质)。构造方法主要是递归,每次构建子树时都需要将数组分成左右两半,左边的构建左子树,右边的构建右子树,中间元素构造根节点。

/**
 * 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 buildBinarySearchTree(nums, 0, nums.length - 1);
    }
    
    public TreeNode buildBinarySearchTree(int[] nums, int start, int end) {
        if(start > end) {
            return null;
        }
        int mid = (start + end) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = buildBinarySearchTree(nums, start, mid - 1);
        root.right = buildBinarySearchTree(nums, mid + 1, end);
        return root;
    }
}
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/d3dde88bcdad
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞