description:
654 | Maximum Binary Tree | 70.2% | Medium |
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:
Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1
Note:
- The size of the given array will be in the range [1,1000].
my solution:
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (nums.size() == 0)
{
return NULL;
} else {
return constructTree(nums, 0, nums.size() - 1);
}
}
private:
TreeNode* constructTree(std::vector<int>& nums, int left, int right) {
int index = 0, max = INT16_MIN;
if(left > right) {
return NULL;
}
for(int i=left; i<=right;i++) {
if(max < nums[i]) {
index = i;
max = nums[i];
}
}
TreeNode* node = new TreeNode(max);
node->left = constructTree(nums,left,index-1);
node->right = constructTree(nums,index+1,right);
return node;
}
};
better ways: by
Mrsuyi
/**
* 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<int>& nums) {
vector<TreeNode*> stk;
for (int i = 0; i < nums.size(); ++i)
{
TreeNode* cur = new TreeNode(nums[i]);
while (!stk.empty() && stk.back()->val < nums[i])
{
cur->left = stk.back();
stk.pop_back();
}
if (!stk.empty())
stk.back()->right = cur;
stk.push_back(cur);
}
return stk.front();
}
};
thought:
按照题目的要求,递归找到结点即可。改良方法在于:
从左到右扫描数字, 扫描一步建立一个节点;
我们使用栈来保存部分树节点, 递减;
对于每个数字, 一直弹出堆栈, 直到null或遇到一个更大的数字;更大的数字是当前数字的根, 并且最后弹出的数字 (如果存在) 是当前结点的右子结点 (暂时, 这种关系可能改变在将来);然后我们将当前数字推入堆栈。