Maximum Binary Tree(C++最大二叉树) - 日理万妓 2022-12-30 03:57 206阅读 0赞 解题思路: (1)使用递归构建左右子树 /** * 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) { auto mp = max_element(nums.begin(),nums.end()); int position = mp-nums.begin(); vector<int> pre,back; for(int i=0;i<nums.size();i++) { if(i<position) pre.push_back(nums[i]); else if(i>position) back.push_back(nums[i]); } TreeNode *root = new TreeNode(*mp); if(!pre.empty()) root->left = constructMaximumBinaryTree(pre); else root->left = NULL; if(!back.empty()) root->right = constructMaximumBinaryTree(back); else root->right = NULL; return root; } };
还没有评论,来说两句吧...