[LeetCode] Maximum Binary Tree

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
/**
* 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 {
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);
}
};
  • monotonic stack solution
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];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/03/PS/LeetCode/maximum-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.