topic
Given an array of non-repeating integers nums
. The maximal binary tree can be constructed recursively from nums with the following algorithm:
- Create a root node whose value
nums
is the largest of . - Recursively build the left subtree on the prefix of the subarray to the left of the maximum.
- Recursively build the right subtree on the subarray suffix to the right of the maximum value.
nums
Returns the largest binary tree constructed .
Example 1:
输入:nums = [3,2,1,6,0,5]
输出:[6,3,5,null,2,0,null,null,1]
解释:递归调用如下所示:
- [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。
- [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。
- 空数组,无子节点。
- [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。
- 空数组,无子节点。
- 只有一个元素,所以子节点是一个值为 1 的节点。
- [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。
- 只有一个元素,所以子节点是一个值为 0 的节点。
- 空数组,无子节点。
Example 2:
输入:nums = [3,2,1]
输出:[3,null,2,null,1]
hint:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
nums
All integers in are different from each other
code
idea: recursion
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* traversal(vector<int>& nums) {
if (nums.size() == 0) return NULL;
//找到数组中最大值
int maxNum = 0, maxIndex = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > maxNum) {
maxNum = nums[i];
maxIndex = i;
}
}
int rootValue = nums[maxIndex];
TreeNode* root = new TreeNode(rootValue);
if (nums.size() == 1) return root;
//左子树分割
vector<int> numsLeft(nums.begin(), nums.begin() + maxIndex);
//右子树分割
vector<int> numsRight(nums.begin() + maxIndex + 1, nums.end());
root->left = traversal(numsLeft);
root->right = traversal(numsRight);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (nums.size() == 0) return NULL;
return traversal(nums);
}
};