思路:文章来源:https://www.toymoban.com/news/detail-515971.html
https://leetcode.cn/problems/maximum-binary-tree/solution/zui-da-er-cha-shu-by-leetcode-solution-lbeo/文章来源地址https://www.toymoban.com/news/detail-515971.html
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
class Solution {
public:
TreeNode* BuildTree(vector<int>& nums) {
return ConverseTree(nums,0,nums.size()-1);
}
TreeNode* ConverseTree(vector<int>& nums,int left,int right) {
if (left > right) {
return NULL;
}
int best = left;
for (int i = left + 1; i <= right; i++) {
if (nums[i] > nums[best])
best = i;
}
TreeNode* Node = new TreeNode(nums[best]);
Node->left = ConverseTree(nums,left,best-1);
Node->right = ConverseTree(nums,best+1,right);
return Node;
}
void print(TreeNode* root) {
if (root == NULL) return;
queue<TreeNode*> que;
if (root != NULL) {
que.push(root);
}
while (!que.empty()) {
TreeNode* Node = que.front();
que.pop();
cout << Node->val << " ";
if (Node->left)que.push(Node->left);
if (Node->right)que.push(Node->right);
}
}
};
int main() {
vector<int> nums = { 3, 2, 1, 6, 0, 5 };
Solution ss;
TreeNode* root = ss.BuildTree(nums);
ss.print(root);
return 0;
}
到了这里,关于654. 最大二叉树的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!