[力扣题解] 654. 最大二叉树

时间:2024-06-09 07:38:25
/** * 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* travel(vector<int>& nums, int start, int end) { // [start, end) if(start == end) { return NULL; } int i, max = -1; for(i = start; i < end; i++) { if(max < nums[i]) { max = nums[i]; } } for(i = start; i < end; i++) { if(max == nums[i]) { break; } } TreeNode* root = new TreeNode(max); // [start, i) root->left = travel(nums, start, i); // [i+1, start) root->right = travel(nums, i+1, end); return root; } TreeNode* constructMaximumBinaryTree(vector<int>& nums) { // [0, nums.size()) return travel(nums, 0, nums.size()); } };