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

    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

    本题要求把有序数组转化成二叉搜索树。二叉搜索树满足性质 左<根<右,对二叉搜索树进行中序遍历将得到有序数组,
    因此有序数组的中间值为根结点,前半部分为左子树,后半部分为右子树,各子树均符合该特性。所以使用二分法的方法进行求解。
    代码如下:
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return arrayToBST(0,nums.size()-1,nums);
        }
        TreeNode* arrayToBST(int left,int right,vector<int>& nums){
            if(left>right)return NULL;
            
            int mid=left+(right-left)/2;
            TreeNode* root= new TreeNode(nums[mid]);
            root->left=arrayToBST(left,mid-1,nums);
            root->right=arrayToBST(mid+1,right,nums);
            return root;
        }
    };


  • 相关阅读:
    05 库的简单操作
    04 基本的MySQL语句
    03 MySQL安装和基本管理
    02 数据库概述
    01 MySQL入门了解
    Django-组件拾遗
    bootstrap基础讲解
    jQuery练习
    前端基础之Jquery
    15 Django组件-中间件
  • 原文地址:https://www.cnblogs.com/cff2121/p/10933162.html
Copyright © 2011-2022 走看看