654. Maximum Binary Tree
You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:
- Create a root node whose value is the maximum value in nums.
- Recursively build the left subtree on the subarray prefix to the left of the maximum value.
- Recursively build the right subtree on the subarray suffix to the right of the maximum value.
Return the maximum binary tree built from nums.
- divide and conquer solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Solution { TreeNode* dnc(vector<int>& A, int l, int r) { if(l > r) return nullptr; int m = max_element(begin(A) + l, begin(A) + r + 1) - begin(A); TreeNode* res = new TreeNode(A[m]); res->left = dnc(A, l, m - 1); res->right = dnc(A, m + 1, r); return res; } public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { return dnc(nums, 0, nums.size() - 1); } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { vector<TreeNode*> st; for(auto& n : nums) { TreeNode* node = new TreeNode(n); while(!st.empty() and st.back()->val < n) { node->left = st.back(); st.pop_back(); } if(!st.empty()) st.back()->right = node; st.push_back(node); } return st[0]; } };
|