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

    题目:

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

    把有序数组转化为二叉搜索树

    解析:

    不会做,看了答案感觉思想很简单,就是将数组中中间的数字当成跟,左子树为(first,mid)右子树为(mid+1,last)

    答案中似乎对所给出的模版函数的参数不满,重新在类中加载了函数

    auto的用法也是亮点,auto一般认为有两个作用:

      一是用来声明自动变量。它是存储类型标识符,表明变量(自动)具有本地范围,块范围的变量声明(如for循环体内的变量声明)默认为auto存储类型。(不需要明确指定auto关键字)

      二是使用auto来代替变量的类型,前提是被明确类型的初始化变量初始化的,可以使用auto关键字比如int i=10; auto a = i; //这样a也是int类型了这在使用一些模板类的时候,对于减少冗赘的代码也很有用

    本例中的mid因为使用了模版类,所以用auto类型比较方便

     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  //时间复杂度 O(n),空间复杂度 O(logn)
    11 class Solution {
    12 public:
    13     TreeNode* sortedArrayToBST (vector<int>& num) {
    14         return sortedArrayToBST(num.begin(), num.end());
    15     }
    16     template<typename RandomAccessIterator>
    17     TreeNode* sortedArrayToBST (RandomAccessIterator first,
    18         RandomAccessIterator last) {
    19             const auto length = distance(first, last);
    20             if (length <= 0) return nullptr; // 终止条件
    21             // 三方合并
    22             auto mid = first + length / 2;
    23             TreeNode* root = new TreeNode (*mid);
    24             root->left = sortedArrayToBST(first, mid);
    25             root->right = sortedArrayToBST(mid + 1, last);
    26             return root;
    27     }
    28 };
  • 相关阅读:
    [论文理解] MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
    [论文理解] Connectionist Text Proposal Network
    [期末复习] 数据结构期末复习
    [机器视觉] 实际场景字提取
    [论文理解]Deep Residual Learning for Image Recognition
    [学习笔记] AD笔记
    [OpenMP] 并行计算入门
    [Docker] Docker安装和简单指令
    python初级装饰器编写
    web页面简单布局的修改,测试中的应用
  • 原文地址:https://www.cnblogs.com/raichen/p/5000637.html
Copyright © 2011-2022 走看看