-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflipBinaryTreeToMatchPreorderTraversal.cpp
More file actions
42 lines (40 loc) · 1.24 KB
/
flipBinaryTreeToMatchPreorderTraversal.cpp
File metadata and controls
42 lines (40 loc) · 1.24 KB
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
// Source: https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/
// Author: Miao Zhang
// Date: 2021-03-29
/**
* 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 {
public:
vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
vector<int> res;
int pos = 0;
solve(root, voyage, pos, res);
if (!res.empty() && res[0] == -1) return {-1};
return res;
}
private:
void solve(TreeNode* root, vector<int>& voyage, int& pos, vector<int>& res) {
if (!root) return;
if (root->val != voyage.at(pos)) {
res.clear();
res.push_back(-1);
return;
}
if (root->left && root->left->val != voyage.at(pos + 1)) {
swap(root->left, root->right);
res.push_back(root->val);
}
pos++;
solve(root->left, voyage, pos, res);
solve(root->right, voyage, pos, res);
}
};