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

来源:互联网 发布:开家淘宝店 编辑:程序博客网 时间:2024/06/05 03:41

描述:

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

样例:

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

     4   /   \  2     6 / \    / \1   3  5   7
标签:递归 二叉树

思路:

采用中间值来作为二叉树的根节点,将原数组分成左右两个新数组;递归的对这两个新数组进行相同的处理。对于每一个根节点,其左右子树的高度相差绝对值不会超过1,满足了二叉平衡树的要求。

代码:

/**
 * 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:
    TreeNode *root;
    TreeNode *sortedArrayToBST(vector<int> &A){
        int left=0,right=A.size()-1;
        root=BuildBST(left,right,A);
        return root;
    }
    TreeNode *BuildBST(int left,int right,vector<int> A){
        if(left>right){
            return NULL;
        }
        int location=(left+right)/2;
        TreeNode *node=new TreeNode(A[location]);
        node->left=BuildBST(left,location-1,A);
        node->right=BuildBST(location+1,right,A);
        return node;
    }
};


阅读全文
0 0