[LeetCode] Flip Binary Tree To Match Preorder Traversal

971. Flip Binary Tree To Match Preorder Traversal

You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.

Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:

Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.

Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* 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 {
bool flag = true;

void isFilp(int& idx, set<int> &res, TreeNode *node, vector<int> &voyage) {
if(voyage[idx] != node->val) {
flag = false;
return;
}
bool left = node->left != nullptr, right = node->right != nullptr;
idx++;
if (left) {
if (voyage[idx] != node->left->val) {
if(right && voyage[idx] == node->right->val) {
res.insert(node->val);
isFilp(idx, res, node->right, voyage);
} else {
flag = false;
}
} else {
isFilp(idx, res, node->left, voyage);
}
}

if (right) {
if (voyage[idx] != node->right->val) {
if(left && voyage[idx] == node->left->val) {
res.insert(node->val);
isFilp(idx,res, node->left, voyage);
} else {
flag = false;
}
} else {
isFilp(idx, res, node->right, voyage);
}
}
}

public:
vector<int> flipMatchVoyage(TreeNode *root, vector<int> &voyage) {
if (root->val != voyage[0])
return vector<int>{-1};

set<int> res;
int idx = 0;
isFilp(idx, res, root, voyage);

return flag ? vector<int>(res.begin(), res.end()) : vector<int>{-1};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/29/PS/LeetCode/flip-binary-tree-to-match-preorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.