美文网首页
951. Flip Equivalent Binary Tree

951. Flip Equivalent Binary Tree

作者: jluemmmm | 来源:发表于2021-11-23 13:04 被阅读0次

    判断两个树是否是翻转二叉树。

    选择任意节点,交换它的左子树和右子树。只要警告一定次数的翻转后,能使x等于y,那么二叉树x翻转等价于二叉树y。

    • Runtime: 114 ms, faster than 13.30%
    • Memory Usage: 40.5 MB, less than 89.45%
    • 时间复杂度O(n),空间复杂度O(n)
    /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} root1
     * @param {TreeNode} root2
     * @return {boolean}
     */
    var flipEquiv = function(root1, root2) {
      if (!root1 && !root2) {
        return true;
      } else if (!root1 || !root2) {
        return false;
      } else if (root1.val !== root2.val) {
        return false;
      }
      return (
        flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) ||
        flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left)
      )
    };
    

    相关文章

      网友评论

          本文标题:951. Flip Equivalent Binary Tree

          本文链接:https://www.haomeiwen.com/subject/gkcitrtx.html