Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
Note:
解题思路:找出最大值,最大值为root,数组左侧为左子树,右侧为右子树,依此递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector& nums) {
return helper(0, nums.size() - 1, nums);
}
TreeNode* helper(int left, int right, vector& nums) {
if (left > right)
return nullptr;
int maxPos = max(nums, left, right);
TreeNode* root = new TreeNode(nums[maxPos]);
root->left = helper(left, maxPos - 1, nums);
root->right = helper(maxPos + 1, right, nums);
return root;
}
int max(vector& nums, int l, int r) {
int Pos = l;
for (int i = l; i <= r; i++) {
if (nums[Pos] < nums[i]){
Pos = i;
}
}
return Pos;
}
};