• LintCode: Convert Sorted Array to Binary Search Tree With Minimal Height


    C++

    复制代码
    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param A: A sorted (increasing order) array
         * @return: A tree node
         */
        TreeNode *sortedArrayToBST(vector<int> &A) {
            // write your code here
            if (0 == A.size()) {
                return NULL;
            }
            return buildTree(A, 0, A.size()-1);
        }
        TreeNode *buildTree(vector<int> &A, int from, int to) {
            if (from > to) {
                return NULL;
            }
            int mid = (from+to)/2;
            TreeNode *node = new TreeNode(A[mid]);
            node->left = buildTree(A, from, mid-1);
            node->right = buildTree(A, mid+1, to);
            return node;
        }
    };
    复制代码

     

    本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5000037.html,如需转载请自行联系原作者

  • 相关阅读:
    WEB API&API
    event flow
    JS-for的衍生对象
    JS-function
    Object Constructor
    前端发展史
    JavaScript中document.getElementById和document.write
    正则表达式把Paul换成Ringo
    11th blog
    10th week blog
  • 原文地址:https://www.cnblogs.com/twodog/p/12138704.html
Copyright © 2020-2023  润新知