小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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

分析

给定一个有序序列,构造一颗平衡的二叉查找树。

思想:序列中值构造根节点,递归,前半序列构造左子树,有伴序列构造右子树。

AC代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if (nums.empty())
            return NULL;

        else
            return make(nums.begin(), nums.end());

    }

    template <typename Iter>
    TreeNode *make(Iter beg, Iter end)
    {
        if (beg == end)
            return NULL;

        //求元素节点个数
        int size = end - beg;

        TreeNode *root = new TreeNode(*(beg + size / 2));

        root->left = make(beg, beg + size / 2);
        root->right = make(beg + size / 2 + 1, end);
        return root;
    }
};

GitHub测试程序源码

posted on 2015-10-17 13:29  Coding菌  阅读(133)  评论(0编辑  收藏  举报