Convert Sorted Array to Binary Search Tree

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

解题思路:此题意思就是给你一组排序好的数组转化为平衡二叉树,既然都是排列好的数组了,我们取中间的元素作为根结点,去中间元素的左边区域的中间元素作为左子结点,去中间元素的右边区域的中间元素作为右子结点。以此类推,使用递归,解之!!!

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void convertToBST(TreeNode *&root,vector<int> &num,int pStart,int pEnd)
    {
        if(pStart>pEnd)
            return;
        int pMid=(pStart+pEnd)/2;
        root=new TreeNode(num[pMid]);
        convertToBST(root->left,num,pStart,pMid-1);
        convertToBST(root->right,num,pMid+1,pEnd);
    }
    TreeNode *sortedArrayToBST(vector<int> &num) {
        if(num.size()<=0)
            return NULL;
        int pStart=0;
        int pEnd=num.size()-1;
        TreeNode *root;
        convertToBST(root,num,pStart,pEnd);
        return root;
    }
};

 

 

 

posted @ 2014-03-14 08:22  Awy  阅读(157)  评论(0编辑  收藏  举报