|
| 1 | +/* |
| 2 | +Flip Binary Tree To Match Preorder Traversal |
| 3 | +============================================ |
| 4 | +
|
| 5 | +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. |
| 6 | +
|
| 7 | +Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. |
| 8 | +
|
| 9 | +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]. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: root = [1,2], voyage = [2,1] |
| 13 | +Output: [-1] |
| 14 | +Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage. |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: root = [1,2,3], voyage = [1,3,2] |
| 18 | +Output: [1] |
| 19 | +Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. |
| 20 | +
|
| 21 | +Example 3: |
| 22 | +Input: root = [1,2,3], voyage = [1,2,3] |
| 23 | +Output: [] |
| 24 | +Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +The number of nodes in the tree is n. |
| 28 | +n == voyage.length |
| 29 | +1 <= n <= 100 |
| 30 | +1 <= Node.val, voyage[i] <= n |
| 31 | +All the values in the tree are unique. |
| 32 | +All the values in voyage are unique. |
| 33 | +*/ |
| 34 | + |
| 35 | +/** |
| 36 | + * Definition for a binary tree node. |
| 37 | + * struct TreeNode { |
| 38 | + * int val; |
| 39 | + * TreeNode *left; |
| 40 | + * TreeNode *right; |
| 41 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 42 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 43 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 44 | + * }; |
| 45 | + */ |
| 46 | + |
| 47 | +class Solution |
| 48 | +{ |
| 49 | +public: |
| 50 | + vector<int> flips; |
| 51 | + int i = 0; |
| 52 | + |
| 53 | + bool preorder(TreeNode *root, vector<int> &v) |
| 54 | + { |
| 55 | + if (root == NULL) |
| 56 | + return true; |
| 57 | + if (root->val != v[i]) |
| 58 | + return false; |
| 59 | + i++; |
| 60 | + |
| 61 | + auto l = root->left, r = root->right; |
| 62 | + if (l != NULL && l->val != v[i]) |
| 63 | + { |
| 64 | + flips.push_back(root->val); |
| 65 | + swap(l, r); |
| 66 | + } |
| 67 | + return preorder(l, v) && preorder(r, v); |
| 68 | + } |
| 69 | + |
| 70 | + vector<int> flipMatchVoyage(TreeNode *root, vector<int> &voyage) |
| 71 | + { |
| 72 | + return preorder(root, voyage) ? flips : vector<int>(1, -1); |
| 73 | + } |
| 74 | +}; |
0 commit comments