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;
        }
    }
};
posted @ 2017-08-03 16:36  LiBaoquan  阅读(235)  评论(0编辑  收藏  举报