Flip Binary Tree To Match Preorder Traversal
Last updated
Was this helpful?
Last updated
Was this helpful?
Given a binary tree withN
nodes, each node has a different value from {1, ..., N}
.
A node in this binary tree can beflipped 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 ofN
values the voyage of the tree.
(Recall that apreorder 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 theleast numberof nodes in the tree so that the voyage of the tree matches thevoyage
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:
Example 2:
Example 3:
Note:
分析
preorder遍历返回bool。比较root and root left的值,不对的话直接翻转继续dfs