• Convert Sorted Array to Binary Search Tree


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

    Analyse: Using binary search to divide the sorted array into two parts, then recursively do the same process for the two parts.

    Runtime: 16ms. 

    Additional: IT'S THE FIRST TIME I COME UP WITH A SOLUTION WITHOUT REFERENCE. CONG!!

     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         if(nums.size() == 0) return NULL;
    14         
    15         return convert(nums, 0, nums.size() - 1);
    16     }
    17     TreeNode* convert(vector<int>& nums, int low, int high){
    18         if(low > high) return NULL;
    19         
    20         int mid = (low + high) / 2;
    21         TreeNode* root = new TreeNode(nums[mid]);
    22         if(low == high) return root;
    23         
    24         root->left = convert(nums, low, mid - 1);
    25         root->right = convert(nums, mid + 1, high);
    26         
    27         return root;
    28     }
    29     
    30 };
  • 相关阅读:
    IDEA效率快捷键
    常用文件/文件夹操作
    git log状态下退出方法
    ImageList 构造函数
    ImageList 控件
    【转】图像分割代码合集
    【转】图像分割论文及代码资源汇总
    SLIC 算法
    c/c++内存分配详解
    c++内存分配
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4691506.html
Copyright © 2020-2023  润新知