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

    Problem:

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

    Analysis:

    Remember a binary search tree's inorder treversal is a sorted array. 

    To convert in the contrary direction, we need to create a node with the middle value of the given array and then create the left treenode with the left part of the array and the right treenode with the right part of the array. Do it recursively!

    Code:

     1 /**
     2  * Definition for binary tree
     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> &num) {
    13         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         return sortedArrayToBSTHelper(num, 0, num.size()-1);
    16     }
    17     
    18     TreeNode *sortedArrayToBSTHelper(vector<int> &num, int lo, int hi) {
    19         if (lo > hi)
    20             return NULL;
    21         
    22         int mid = (lo + hi) / 2;
    23         TreeNode *node = new TreeNode(num[mid]);
    24         node->left = sortedArrayToBSTHelper(num, lo, mid-1);
    25         node->right = sortedArrayToBSTHelper(num, mid+1, hi);
    26         
    27         return node;
    28     }
    29 };
    View Code

    Attention:

    To create an object in C++, either the following two ways:

    1. SomeClass obj(para);

    2. SomeClass *obj = new SomeClass(para);

    The 1st will return an object, while the 2nd will return a pointer.

  • 相关阅读:
    C指针详解(经典,非常详细)
    PL/SQL错误提示 database character set(AL32UTF8) and Client character set(ZHS16GBK) are different
    安装Oracle报错,全部为未知!
    Oracle 支持在具有 DHCP 分配的 IP 地址的系统上进行安装
    Asp.Net页面生命周期
    oracle 导库建立测试库
    宝塔安装建站教程
    SEM理论
    SEM小总结
    SEM大致操作梳理
  • 原文地址:https://www.cnblogs.com/freeneng/p/3087979.html
Copyright © 2011-2022 走看看