【LeetCode】951. Flip Equivalent Binary Trees

【LeetCode】951. Flip Equivalent Binary Trees_第1张图片

题目大意:给定两棵树,判断经过一系列旋转操作后是否相等。

刚开始写就想设一个旋转操作,遇到不等的节点就旋转再判断,代码又臭又长。

看了一下讨论区,恍然大悟,原来并不需要真正的旋转,将遍历的顺序改变一下其实就相当于做了旋转:
 

/**
 * 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 {
public:
    bool flipEquiv(TreeNode* root1, TreeNode* root2) {
        if ((root1==NULL && root2!=NULL) || (root1!=NULL && root2==NULL))
        {            
            return false;            
        } 
        else if (root1!= NULL) 
        {  
        /*which means none of them is NULL, 
        since with previous if condition we made sure both of them are NULL 
        or none of them is NULL*/
            return ( (root1->val ==root2->val) && (
                    (flipEquiv (root1->right, root2->left) && 
                     flipEquiv (root1->left, root2->right) )  ||
                    (flipEquiv (root1->left, root2->left) && 
                     flipEquiv (root1->right, root2->right) )  )  );                              
        } else 
            return true;        
    }
};

 参考:https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/200499/C%2B%2B-solution-Recursive-with-illustrated-explanation-and-example

你可能感兴趣的:(LeetCode)