LeetCode题解:Convert Sorted Array to Binary Search Tree


Convert Sorted Array to Binary Search Tree


Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:
给定一个区间[left, right],取其中值mid=(left+right)/2对应的元素作为二叉树的根。二叉树的左子树根的值为对[left, mid-1]继续操作的结果,右子树类似。
题解:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* generateBST(int left, int right, vector<int>& num)
    {
        if (left > right)
            return nullptr;
        else if (left == right)
            return new TreeNode(num[left]);
        else
        {
            int mid = (left + right) / 2;
            TreeNode* node = new TreeNode(num[mid]);
            node->left = generateBST(left, mid - 1, num);
            node->right = generateBST(mid + 1, right, num);
            return node;
        }
    }

    TreeNode *sortedArrayToBST(vector<int> &num) {
        return generateBST(0, num.size() - 1, num);
    }
};


你可能感兴趣的:(LeetCode)