注意中点的取值,以及终止条件
class Solution { public: /** * * @param num int整型vector * @return TreeNode类 */ TreeNode *sortedArrayToBST(vector<int> &num) { if (num.size() < 1) return nullptr; TreeNode *root = preOrder(num, 0, num.size() - 1); return root; } TreeNode *preOrder(vector<int> &num, int left, int right) { if (left > right) return nullptr;//注意是,左大于右 // 1. 找到中间节点 int mid = left + (right - left + 1) / 2;//注意这个中点的取值方法 // 2. 递归构建左右 TreeNode *root = new TreeNode(num[mid]); root->left = preOrder(num, left, mid - 1); root->right = preOrder(num, mid + 1, right); return root; } };