题目链接
class Solution {
public:
TreeNode* traver(vector<int> nums, int left, int right) {
if (left >= right) return NULL;
int maxIndex = left;
for (int i = left+1; i < right; i++) {
if (nums[i] > nums[maxIndex])
maxIndex = i;
}
TreeNode* node = new TreeNode(nums[maxIndex]);
node->left = traver(nums, left, maxIndex);
node->right = traver(nums, maxIndex+1, right);
return node;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
int left = 0;
int right = nums.size();
return traver(nums, left, right);
}
};
总结
- 采用先序遍历
- 左开右闭区间
- 找到最大值的下标maxIndex,构建根节点
- 递归构造左子树、右子树
|