Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
- The root is the maximum number in the array.
- The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
- The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
1 2 3 4 5 6 7 8 9 10 |
Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1 |
Idea:
Recursion
Solution:
With copy
Time complexity: O(nlogn) ~ O(n^2)
Space complexity: O(nlogn) ~ O(n^2)
running time 79ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { if(nums.empty()) return nullptr; auto it = std::max_element(nums.begin(), nums.end()); TreeNode* root=new TreeNode(*it); vector<int> left(nums.begin(), it); vector<int> right(it+1, nums.end()); root->left = constructMaximumBinaryTree(left); root->right = constructMaximumBinaryTree(right); return root; } } |
Without copy
Time complexity: O(nlogn) ~ O(n^2)
Space complexity: O(logn) ~ O(n)
running time 66ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { return makeMBT(nums, 0, nums.size()); } private: TreeNode* makeMBT(const vector<int>& nums, int begin, int end) { if(begin>=end) return nullptr; auto it = std::max_element(nums.begin() + begin, nums.begin() + end); TreeNode* root=new TreeNode(*it); int index = it - nums.begin(); root->left = makeMBT(nums, begin, index); root->right = makeMBT(nums, index+1, end); return root; } }; |