leetcode 971. Flip Binary Tree To Match Preorder Traversal
题意:给一颗二叉树,再给一个的数组,能否通过交换两个左右两个子节点,使得二叉树的前序遍历是给的数组。并保留交换节点的父节点。
思路:如果能交换成功,那么交换的顺序肯定唯一,所以只要按前序遍历,模拟一下就好了。过程和剑指offer里面的 二叉树的镜像 有点类似。
class Solution {
public:
vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
pos = 0;
vector<int> ans;
if (gao(root, voyage, ans))
return ans;
else
return vector<int>{-1};
}
bool gao(TreeNode* root, vector<int>& voyage, vector<int>& ans)
{
if (root == nullptr) return true;
if (root->val != voyage[pos]) return false;
pos++;
if (root->left != nullptr && root->right != nullptr)
{
if (root->right->val == voyage[pos])
{
ans.push_back(root->val);
return gao(root->right, voyage, ans) && gao(root->left, voyage, ans);
}
return gao(root->left, voyage, ans) && gao(root->right, voyage, ans);
}
else
return gao(root->left, voyage, ans) && gao(root->right, voyage, ans);
}
private:
int pos;
};