当前位置: 代码迷 >> 综合 >> leetcode 971. Flip Binary Tree To Match Preorder Traversal
  详细解决方案

leetcode 971. Flip Binary Tree To Match Preorder Traversal

热度:12   发布时间:2024-01-16 17:59:47.0

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;elsereturn 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);}elsereturn gao(root->left, voyage, ans) && gao(root->right, voyage, ans);}private:int pos;};

 

  相关解决方案