zoukankan      html  css  js  c++  java
  • 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


    用一个已排序的数组构建一个平衡二叉搜索树

    C++(16ms):
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* sortedArrayToBST(vector<int>& nums) {
    13         int len = nums.size() ;
    14         if (len == 0)
    15             return NULL ;
    16         if (len == 1)
    17             return new TreeNode(nums[0]) ;
    18         int mid = len/2 ;
    19         TreeNode* root = new TreeNode(nums[mid]) ;
    20         vector<int> leftArr(nums.begin() , nums.begin()+mid ) ;
    21         vector<int> rightArr(nums.begin()+mid+1 , nums.end() ) ;
    22         root->left = sortedArrayToBST(leftArr) ;
    23         root->right = sortedArrayToBST(rightArr) ;
    24         return root ;
    25     }
    26 };
     
  • 相关阅读:
    nginx把POST转GET请求解决405问题
    Redis安装与配置
    SQL语句-SELECT语句
    SQL语句-delete语句
    SQL语句-UPDATE语句
    SQL语句-INSERT语句
    SQL语句-create语句
    MySQL权限详解
    GTID复制详解
    ansible-playbook的应用实例
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8575506.html
Copyright © 2011-2022 走看看