2
* Definition for a binary tree node.7
* TreeNode() : val(0), left(nullptr), right(nullptr) {}8
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}9
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),15
TreeNode *canMerge(vector<TreeNode *> &trees) {16
// store the leaves of every node18
unordered_map<int, TreeNode *> mp;20
// store the current min and current max nodes in the current tree21
unordered_map<TreeNode *, pair<int, int>> mini;22
for (int i = 0; i < trees.size(); i++) {23
pair<int, int> ans = {trees[i]->val, trees[i]->val};25
mp[trees[i]->left->val] = {trees[i]};26
ans.first = trees[i]->left->val;28
if (trees[i]->right) {29
mp[trees[i]->right->val] = trees[i];30
ans.second = trees[i]->right->val;35
// store the number of merging operations we will be doing38
TreeNode *root = NULL;39
// now for every node get the root40
for (int i = 0; i < trees.size(); i++) {41
// if the current tree can be merged into some other tree42
if (mp.find(trees[i]->val) != mp.end()) {45
TreeNode *parent = mp[trees[i]->val];46
if (trees[i]->val < parent->val) {49
// if the maximum of the current sub tree is greater than the parent50
// value then return NULL51
if (parent->val <= mini[trees[i]].second) return NULL;52
// change the minimum value of the parent tree to the current min54
mini[parent].first = mini[trees[i]].first;56
parent->left = trees[i];57
} else if (trees[i]->val > parent->val) {60
// if the minimum of the current tree is lesser than the parent value63
if (parent->val >= mini[trees[i]].first) return NULL;65
// change the parent tree maximum to the current tree maximum66
mini[parent].second = mini[trees[i]].second;68
parent->right = trees[i];70
// erase the current tree value71
mp.erase(trees[i]->val);73
// it has no other tree to merge74
// it is the root node we should return83
// if we are not able to merge all trees return NULL84
if (count != trees.size() - 1) return NULL;