951. 翻转等价二叉树【划水刷题】

题目链接

951. 翻转等价二叉树

题解

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function flipEquiv(root1: TreeNode | null, root2: TreeNode | null): boolean {
    // root1为空树,root2也为空树,
    if (!root1 && !root2) return true
    // root1为空树,root2不为空树,
    if (!root1 && root2) return false
    // root1不为空树,root2为空树,
    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
    // 比较root1左子树和root2的右子树和root1的右子树与root2的左子树
    if (flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left)) return true
    return false
};

你可能感兴趣的:(算法小抄,算法,leetcode,数据结构)