• lintcode-177-把排序数组转换为高度最小的二叉搜索树


    177-把排序数组转换为高度最小的二叉搜索树

    给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

    注意事项

    There may exist multiple valid solutions, return any of them.

    样例

    给出数组 [1,2,3,4,5,6,7], 返回

    标签

    递归 二叉树 Cracking The Coding Interview

    思路

    对数组进行二分遍历,遍历的同时建立排序二叉树

    code

    /**
     * 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
            int size = A.size();
            if (size <= 0) {
                return nullptr;
            }
            TreeNode *root;
            root = sortedArrayToBST(A, 0, size-1);
            return root;
        }
        TreeNode * sortedArrayToBST(vector<int> &A,  int low, int high) {
            if (low <= high) {
                int mid = low + (high - low) / 2;
                TreeNode * root = new TreeNode(A[mid]);
                root->left = sortedArrayToBST(A, low, mid - 1);
                root->right = sortedArrayToBST(A, mid + 1, high);
                return root;
            }
            else {
                return nullptr;
            }
        }
    };
    
  • 相关阅读:
    csp2020游记
    agc006_f Blackout
    CF1368G Shifting Dominoes
    AtCoder Grand Contest 009 简要题解
    Codeforces Round #666 (Div. 1)
    CSP 2019 树的重心
    Luogu-P4859 已经没什么好害怕的了
    2020.9.17 校内测试
    CF379F New Year Tree
    图论(小结论)
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7280459.html
Copyright © 2020-2023  润新知