Skip to content

951. Flip Equivalent Binary Trees

951. Flip Equivalent Binary Trees

题目: https://leetcode.com/problems/flip-equivalent-binary-trees/

难度: Medium

题意:

  1. 给两棵树
  2. 两棵树可以做交换左右子树的操作
  3. 求两棵树是否能通过某些操作,使得两棵树一模一样

思路:

  • 递归判断
  • 两个都为空,返回true
  • 一个为空,返回false
  • 根的值不同,返回false
  • 递归判断左子树和右子树,判断左右两棵对应的子树是否为true,或者交换下子树,判断是否为true,返回true
  • 其他情况返回false

解法:

/**
 * 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 && !root2) {
            return true;
        }
        if (!root1 || !root2) {
            return false;
        } 
        if (root1->val != root2->val) {
            return false;
        }
        if (flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right)) {
            return true;
        }
        if (flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left)) {
            return true;
        }
        return false;
    }
};

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组