题目描述
原题链接:654. 最大二叉树
解题思路
思路与106. 从中序与后序遍历序列构造二叉树(递归法)相同,找到最大值作为分割点。再往下递归的去分割左、右子树,直至只剩一个结点时,返回该节点。
一、递归法
/**
* 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* constructMaximumBinaryTree(vector<int>& nums) {
if(nums.size() == 0) return NULL;
int maxvalue = *max_element(nums.begin(), nums.end());
TreeNode* node = new TreeNode(maxvalue);
if(nums.size() == 1) return node;
int maxindex = 0;
while(nums[maxindex] != maxvalue) maxindex++;
vector<int> leftvalue(nums.begin(), nums.begin() + maxindex);
vector<int> rightvalue(nums.begin() + maxindex + 1, nums.end());
node->left = constructMaximumBinaryTree(leftvalue);
node->right = constructMaximumBinaryTree(rightvalue);
return node;
}
};
参考文章:654.最大二叉树