zoukankan      html  css  js  c++  java
  • Leetcode 108. Convert Sorted Array to Binary Search Tree

    题目链接

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

    题目描述

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

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    Example:

    Given the sorted array: [-10,-3,0,5,9],
    
    One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
    
          0
         / 
       -3   9
       /   /
     -10  5
    
    

    题解

    数组是已经排好序,我们可以取数组的中间节点作为根节点,这样构造的二叉树每个节点的左右两个子树的高度差的绝对值不超过1.

    代码

    /**
     * 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 sortedArrayBST(nums, 0, nums.length - 1);
        }
        public TreeNode sortedArrayBST(int[] a, int lo, int hi) {
            if (lo > hi) { return null; }
            if (lo == hi) { return new TreeNode(a[lo]); }
            int mid = (lo + hi) >> 1;
            TreeNode root = new TreeNode(a[mid]);
            root.left = sortedArrayBST(a, lo, mid - 1);
            root.right = sortedArrayBST(a, mid + 1, hi);
            return root;
        }
    }
    
    
  • 相关阅读:
    算法导论————KMP
    KMP算法
    几个很好的OJ网站
    查找(二分、hash、桶)
    动态规划
    贪心(未完待续)
    搜索的题
    codeVS 1031 质数环
    《将博客搬至CSDN》
    HDU1717小数化分数2
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9547447.html
Copyright © 2011-2022 走看看