Given a binary tree with N
nodes, each node has a different value from {1, ..., N}
.
A node in this binary tree can be flipped by swapping the left child and the right child of that node.
Consider the sequence of N
values reported by a preorder traversal starting from the root. Call such a sequence of N
values the voyage of the tree.
(Recall that a preorder traversal of a node means we report the current node’s value, then preorder-traverse the left child, then preorder-traverse the right child.)
Our goal is to flip the least number of nodes in the tree so that the voyage of the tree matches the voyage
we are given.
If we can do so, then return a list of the values of all nodes flipped. You may return the answer in any order.
If we cannot do so, then return the list [-1]
.
Example 1:
Input: root = [1,2], voyage = [2,1] Output: [-1]
Example 2:
Input: root = [1,2,3], voyage = [1,3,2] Output: [1]
Example 3:
Input: root = [1,2,3], voyage = [1,2,3] Output: []
Note:
1 <= N <= 100
Solution: Pre-order traversal
if root->val != v[pos] return [-1]
if root->left?->val != v[pos + 1], swap the nodes
c++
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 |
class Solution { public: vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) { vector<int> flips; int pos = 0; solve(root, voyage, pos, flips); return flips; } private: void solve(TreeNode* root, const vector<int>& voyage, int& pos, vector<int>& flips) { if (!root) return; if (root->val != voyage.at(pos)) { flips.clear(); flips.push_back(-1); return; } if (root->left && root->left->val != voyage.at(pos + 1)) { swap(root->left, root->right); flips.push_back(root->val); } ++pos; solve(root->left, voyage, pos, flips); solve(root->right, voyage, pos, flips); } }; |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Author: Huahua, 60 ms class Solution: def flipMatchVoyage(self, root, voyage): self.pos = 0 self.flips = [] def solve(root): if not root: return if root.val != voyage[self.pos]: self.flips = [-1] return if root.left and root.left.val != voyage[self.pos + 1]: root.left, root.right = root.right, root.left self.flips.append(root.val) self.pos += 1 solve(root.left) solve(root.right) solve(root) return self.flips |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment