Flip Binary Tree To Match Preorder Traversal LeetCode solution in C++

1
class Solution {
2
public:
3
bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans) {
4
if (root == NULL || ind == voyage.size()) {
5
ind--;
6
return true;
7
}
8

9
// Not possible to create
10
if (root->val != voyage[ind]) {
11
ans.clear();
12
ans.push_back(-1);
13
return false;
14
}
15

16
// If voyage value not equal to its left child, then swap both childs and
17
// check
18
if (root->left && root->left->val != voyage[ind + 1]) {
19
TreeNode *temp = root->left;
20
root->left = root->right;
21
root->right = temp;
22

23
// Pusing root into ans
24
ans.push_back(root->val);
25
}
26

27
return helper(++ind, root->left, voyage, ans) && helper(++ind, root->right, voyage, ans);
28
}
29

30
vector<int> flipMatchVoyage(TreeNode *root, vector<int> &voyage) {
31
int ind = 0;
32
vector<int> ans;
33
helper(ind, root, voyage, ans);
34
return ans;
35
}
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0