编程问题:
给你一棵二叉树的根节点 root ,树中有 n 个节点,每个节点都有一个不同于其他节点且处于 1 到 n 之间的值。另给你一个由 n 个值组成的行程序列 voyage ,表示 预期 的二叉树 先序遍历 结果。请翻转 最少 的树中节点,使二叉树的 先序遍历 与预期的遍历行程 voyage 相匹配 。 如果可以,则返回 翻转的 所有节点的值的列表。你可以按任何顺序返回答案。如果不能,则返回列表 [-1]。
示例:
- 输入:root = [1,2], voyage = [2,1]
输出:[-1]
解释:翻转节点无法令先序遍历匹配预期行程。 - 输入:root = [1,2,3], voyage = [1,3,2]
输出:[1]
解释:交换节点 2 和 3 来翻转节点 1 ,先序遍历可以匹配预期行程。 - 输入:root = [1,2,3], voyage = [1,2,3]
输出:[]
解释:先序遍历已经匹配预期行程,所以不需要翻转节点。
解法:
1.深度优先遍历
时间复杂度O(N)
空间复杂度O(N)
/**
* 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 {
private:
bool dfs(TreeNode *root, vector<int>& voyage)
{
if (!root)
return true;
else if (index >= voyage.size())
return false;
if (root->val != voyage[index])
return false;
index++;
if (dfs(root->left, voyage) && dfs(root->right, voyage))
return true;
if (dfs(root->right, voyage) && dfs(root->left, voyage))
{
res.push_back(root->val);
return true;
}
return false;
}
public:
int index = 0;
vector<int> res;
vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
if (dfs(root, voyage))
return res;
return vector<int> {-1};
}
};