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 };
  • 相关阅读:
    20165306 Exp4 恶意代码分析
    20165306 Exp3 免杀原理与实践
    20165306 Exp2 后门原理与实践
    20165306 Exp1 PC平台逆向破解
    20165306 Exp0 Kali安装 Week1
    2018-2019-2 网络对抗技术 20165216 Exp9 Web安全基础
    2018-2019-2 网络对抗技术 20165216 Exp8 WEB基础
    2018-2019-2 网络对抗技术 20165216 Exp7 网络欺诈防范
    2018-2019-2 网络对抗技术 20165216 Exp6 Exp6 信息搜集与漏洞扫描
    2018-2019-2 网络对抗技术 20165216 Exp5 MSF基础应用
  • 原文地址:https://www.cnblogs.com/raichen/p/5000637.html
Copyright © 2011-2022 走看看