/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int n,ans=1; public: void dfs(TreeNode* root){ if(!root) return; if(!root->left&&!root->right){return;} if(root->left&&!root->right){dfs(root->left);return;} if(!root->left&&root->right){root->left=root->right;root->right=NULL;dfs(root->left);return;} if(root->left->val>root->right->val){ swap(root->left,root->right); } dfs(root->left); dfs(root->right); } void judge(TreeNode* root1,TreeNode* root2){ if((root1==NULL&&root2!=NULL)||(root1!=NULL&&root2==NULL)){ans=0;return;} if(!root1) return; if(root1->val!=root2->val){ans=0;return;} judge(root1->left,root2->left); judge(root1->right,root2->right); } bool flipEquiv(TreeNode* root1, TreeNode* root2) { //转成左偏树, n=0; dfs(root1); int a1=n; n=0; dfs(root2); if(a1!=n) return 0; judge(root1,root2); return ans; } };
注意翻转后进行单枝递归,并return