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

    题目链接

    Problem discription:

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

    Accepted 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, int start, int end) {
    13         if (start > end) {
    14             return NULL;
    15         } 
    16         // if you write " int middle = start + (end - start) >> 1"
    17         // instead of the following sentence, you should keep in 
    18         // mind that the priority of ">>" is weaker than "+" operator
    19         int middle = start + (end - start) / 2;
    20         TreeNode *p = new TreeNode(num[middle]);
    21         // elements at the left of num[middle] construct
    22         // the left child tree of "p" and its right child
    23         // tree consists of elements located at the right
    24         // of num[middle]...
    25         // because the given array is sorted
    26         if (start != end) {
    27             p->left = sortedArrayToBST(num, start, middle - 1);
    28             p->right = sortedArrayToBST(num, middle + 1, end);
    29         }
    30         return p;
    31     }
    32     TreeNode *sortedArrayToBST(vector<int> &num) {
    33         // call the overload function
    34         return sortedArrayToBST(num, 0, num.size() - 1);
    35     }
    36 };
  • 相关阅读:
    VS快速格式化代码
    EasyUI——实现展示后台数据代码
    并行开发
    EF---结合三层方法的应用
    EF—主键冲突解决办法
    SVN——配置和安装
    谈谈MVC模式
    JDK/Java里的设计模式
    设计模式的设计原则和精神
    举例说明你使用的设计模式
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3788490.html
Copyright © 2011-2022 走看看