最大二叉树
vector的最大值最小值
- 最大值
auto max_val = max_element(nums.begin() , nums.end()); cout<<"最大值"<<*max_val<<"最大值下标"<<max_val - nums.begin()<<endl;
- 最小值
auto min_val = min_element(nums.begin() , nums.end()); cout<<"最小值"<<*min_val <<"最小值下标"<<min_val - nums.begin()<<endl;
递归法
/** * 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* get_big_tree(vector<int>& nums) { if(nums.size() == 0) return nullptr; TreeNode* root = new TreeNode; auto max_val = max_element(nums.begin() , nums.end()); root->val = *max_val; // cout<<*max_val<<' '<<max_val - nums.begin()<<endl; vector<int> left_nums(nums.begin() , max_val ); vector<int> right_nums( max_val + 1 , nums.end()); root->left = get_big_tree(left_nums); root->right = get_big_tree(right_nums); return root; } TreeNode* constructMaximumBinaryTree(vector<int>& nums) { if(nums.size() == 0) return nullptr; return get_big_tree(nums); } };
二刷
/** * 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* track_back(vector<int>& nums) { if(nums.size()==0) return nullptr; int max_num = 0; for(int i=0 ; i<nums.size();i++) if( nums[i] > nums[max_num] ) max_num = i; TreeNode* root = new TreeNode(nums[max_num]); if(nums.size() ==1 ) return root; vector<int> leftNums(nums.begin() , nums.begin() + max_num ); vector<int> rightNums(nums.begin() + max_num +1 , nums.end()); root->left = track_back(leftNums); root->right = track_back(rightNums); return root; } TreeNode* constructMaximumBinaryTree(vector<int>& nums) { TreeNode* root = track_back(nums); return root; } };