zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    };
    
  • 相关阅读:
    Python阶段复习
    Python阶段复习
    Python学习笔记
    Python爬虫学习
    Python爬虫学习
    Python学习笔记
    史上最全的Maven Pom文件标签详解
    css3 animation动画技巧
    常用的sass编译库
    compass做雪碧图
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7280459.html
Copyright © 2011-2022 走看看